DB2存储过程实现查询表数据,生成动态SQL,并执行
一、动态执行SQL
PREPARE S1 FROM 'delete from test'; EXECUTE S1;
二、使用游标
DECLARE V_CURSOR CURSOR FOR SELECT DELETESQL,INSERTSQL FROM FJDC.V_I_DG_DM_ZY_WL_ZBHZ_ATTR T; OPEN V_CURSOR; FETCH V_CURSOR INTO V_DELETESQL,V_INSERTSQL; CLOSE V_CURSOR;
三、WHILE循环
WHILE true DO 表达式 END WHILE;
四、DB2查询表数据,生成动态SQL,并执行
1 CREATE PROCEDURE "TEST"."TEST" () 2 BEGIN 3 DECLARE V_DELETESQL VARCHAR(2000); 4 DECLARE V_INSERTSQL VARCHAR(2000); 5 DECLARE I_COUNT INT; 6 7 --确定循环次数 8 SELECT COUNT(INSERTSQL) INTO I_COUNT FROM FJDC.V_I_DG_DM_ZY_WL_ZBHZ_ATTR T; 9 IF I_COUNT > 0 THEN 10 --游标 11 DECLARE V_CURSOR CURSOR FOR 12 SELECT DELETESQL,INSERTSQL FROM FJDC.V_I_DG_DM_ZY_WL_ZBHZ_ATTR T; 13 14 OPEN V_CURSOR; 15 WHILE I_COUNT > 0 DO 16 SET I_COUNT = I_COUNT-1; 17 FETCH V_CURSOR INTO V_DELETESQL,V_INSERTSQL; 18 19 --执行动态SQL 20 PREPARE S1 FROM V_DELETESQL; 21 EXECUTE S1; 22 23 PREPARE S1 FROM V_INSERTSQL; 24 EXECUTE S1; 25 26 END WHILE; 27 CLOSE V_CURSOR; 28 29 END IF; 30 END