Sample code:
DROP PROCEDURE Quotation. Copy_sample; CREATE PROCEDURE Quotation. Copy_sample (in Tablenamefrom varchar (+), in Tablenameto varchar (+), INOUT copyresult INTEGER) BEGIN Decla RE 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 = 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;
Note the point:
1. Sqlcode must be defined and must be defined below the outermost begin.
2, must judge whether the Sqlcode equals 100, is equal to 100 when exits cursorloop, otherwise will die cycle.
3, "OPEN curs" do not forget after "Cursorloop:".
4, in DB2 Dynamic SQL if the inclusion of select or values is not directly executed (such as: In the above code: PREPARE s from Tosql; EXECUTE s;), you must use the "OPEN curs" notation.
Executing dynamic SQL in a DB2 stored procedure