我是 DB2 和存储过程的新手。我想在 DB2 中编写一个存储过程来更新表。该过程有一个 XML 文档作为其输入参数。
我需要遍历 XML 的每条记录,选择一些节点并更新表中的相应行。此存储过程将用于批量更新表。
我有过程的伪代码,但不确定它在 DB2 中的外观。
INPUT XML 的格式为
<Root>
<Record>
<a>1234</a>
<b>1</b>
<c>2</c>
<d>A</d>
<e>B</e>
<f>C</f>
</Record>
<Record>
<a>1235</a>
<b>1</b>
<c>2</c>
<d>A</d>
<e>B</e>
<f>C</f>
</Record>
</Root>
该过程将类似于
CREATE PROCEDURE UPDATE_BATCH (IN INDOC XML)
P1: BEGIN
FOR rec AS rec CURSOR FOR(
SELECT
Record.XMLQUERY('//Record/a/text()') AS A,
Record.XMLQUERY('//Record/b/text()') AS B,
Record.XMLQUERY('//Record/c/text()') AS C,
Record.XMLQUERY('//Record/d/text()') AS D,
Record.XMLQUERY('//Record/e/text()') AS E,
Record.XMLQUERY('//Record/f/text()') AS F
FROM
TABLE (INDOC)Record--Not Sure how to construct table from input xml
)
DO
UPDATE XYZ.TEMP_TABLE
SET ACOL=Record.A,
BCOL=Record.B,
CCOL=Record.C,
DCOL=Record.D,
ECOL=Record.E
WHERE
FCOL=Record.F;
END FOR;
END P1
请帮我创建上述程序。我无法在 DB2 中获得 ForEach、XML 节点处理、CURSOR 和 LOOPING 的正确语法。
回答
CREATE PROCEDURE UPDATE_BATCH(IN DOC XML)
BEGIN
MERGE INTO XYZ.TEMP_TABLE AS T
USING (SELECT X.* FROM
XMLTABLE('$d/Root/Record' passing DOC as "d"
COLUMNS
"A" VARCHAR(10) PATH 'a',
"B" VARCHAR(10) PATH 'b',
"C" VARCHAR(10) PATH 'c',
"D" VARCHAR(10) PATH 'd',
"E" VARCHAR(10) PATH 'e',
"F" VARCHAR(10) PATH 'f'
) AS X) AS XT
ON T.FCOL=XT."F"
WHEN MATCHED THEN
UPDATE
SET
T.ACOL=XT."A",
T.BCOL=XT."B",
T.COL=XT."C"
END