DB2 中的循环游标变量
Loop cursor variable in DB2
CREATE OR REPLACE PROCEDURE qqq ()
P1: BEGIN
Declare cID char(5) ;
Declare cc char(5) ;
Declare SQLSTATE char(5) default '00000' ;
declare stmt varchar(1000) ;
declare c1 cursor for s1 ;
set cid = 'b' ;
Set stmt = 'select * from aaa where a = ?' ;
prePare s1 from stmt ;
open c1 using cid ;
ins_loop :
Loop
fetch c1 into cc ;
if SQLSTATE <> '00000' then LEAVE ins_loop ; end if ;
insert into bbb (aa) values ('3' || cc) ;
end loop ins_loop;
close c1 ;
commit ;
END P1
在 运行 之后,table bbb 为空。如果正确,则 table bbb 有 2 行。因为查询( select * from aaa where a = 'b' )有 2 行。
如果您的 table 包含超过 1 列,您会得到 SQLSTATE = 01503。这是一个警告(不是例外),因此您的 SP 会继续执行。
使用 select column_name from ...
或适当修改 SQLSTATE <> '00000'
条件。
P.S.: 不要在你的 SP 中使用 commit
除非真的有必要。在这种情况下没关系,但在调用应用程序管理事务时更好。
CREATE OR REPLACE PROCEDURE qqq ()
P1: BEGIN
Declare cID char(5) ;
Declare cc char(5) ;
Declare SQLSTATE char(5) default '00000' ;
declare stmt varchar(1000) ;
declare c1 cursor for s1 ;
set cid = 'b' ;
Set stmt = 'select * from aaa where a = ?' ;
prePare s1 from stmt ;
open c1 using cid ;
ins_loop :
Loop
fetch c1 into cc ;
if SQLSTATE <> '00000' then LEAVE ins_loop ; end if ;
insert into bbb (aa) values ('3' || cc) ;
end loop ins_loop;
close c1 ;
commit ;
END P1
在 运行 之后,table bbb 为空。如果正确,则 table bbb 有 2 行。因为查询( select * from aaa where a = 'b' )有 2 行。
如果您的 table 包含超过 1 列,您会得到 SQLSTATE = 01503。这是一个警告(不是例外),因此您的 SP 会继续执行。
使用 select column_name from ...
或适当修改 SQLSTATE <> '00000'
条件。
P.S.: 不要在你的 SP 中使用 commit
除非真的有必要。在这种情况下没关系,但在调用应用程序管理事务时更好。