样本代码:
DROP PROCEDURE QUOTATION.COPY_SAMPLE;
CREATE PROCEDURE QUOTATION.COPY_SAMPLE (
IN tableNameFrom VARCHAR(30)
, IN tableNameTo VARCHAR(30)
, INOUT copyResult INTEGER)
BEGIN
DECLARE SQLCODE INTEGER DEFAULT 0;
SET copyResult = 0;
-- Proecss 1
BEGIN
DECLARE fromSql VARCHAR(32672);
DECLARE toSql VARCHAR(32672);
DECLARE templateParserId INTEGER;
DECLARE uuid VARCHAR(36);
DECLARE stmt STATEMENT;
DECLARE curs CURSOR FOR stmt;
SET fromSql = ‘SELECT TEMPLATE_PARSER_ID, UUID FROM QUOTATION.‘ || tableNameFrom;
PREPARE stmt FROM fromSql;
OPEN curs;
CURSORLOOP:
LOOP
FETCH curs INTO templateParserId, uuid;
-- Do nothing if no data or processed all datas.
IF SQLCODE = 100 THEN LEAVE CURSORLOOP;
END IF;
SET toSql = ‘INSERT INTO QUOTATION.‘ || tableNameTo || ‘ (TEMPLATE_PARSER_ID, UUID) VALUES (‘ || templateParserId || ‘,‘‘‘ || uuid || ‘‘‘)‘;
PREPARE s FROM toSql;
EXECUTE s;
END LOOP;
CLOSE curs;
END;
-- Proecss 2
BEGIN
-- ......
END;
SET copyResult = 1;
END;
注意点:
1、SQLCODE必须要定义,且必须定义在最外层的BEGIN的下面。
2、必须要判断SQLCODE是否等于100,等于100时退出CURSORLOOP,否则会死循环。
3、“OPEN curs”之后不要忘记“CURSORLOOP:”。
4、在DB2中动态SQL中如果包含SELECT或者VALUES是不能直接执行的(如:以上代码中的:PREPARE s FROM toSql;EXECUTE s;),必须使用“OPEN curs”的写法。
原文地址:http://blog.51cto.com/13685327/2146247
时间: 2024-11-05 19:43:36