电脑技术学习

用一个实例讲解DB2数据库游标循环的问题

dn001
本文中的存储过程示例,预计的循环次数是yh表行数,由于SELECT IID INTO PINT FROM YH WHERE 0=1;不返回任何行,所以at_end后会立刻等于1(只循环一次就退出)。

DECLARE  at_end  INT  DEFAULT  0;  
DECLARE PIID INTEGER DEFAULT 0 ;
DECLARE PINT INTEGER DEFAULT 0 ; 
DECLARE  not_found  CONDITION  FOR  SQLSTATE  '02000';
--DECLARE PCOUNT INTEGER;
DECLARE  c1  CURSOR  FOR    
SELECT IID FROM YH;  
DECLARE  CONTINUE  HANDLER  FOR  not_found  
SET  at_end  =  1;  
OPEN  c1;  
SET PCOUNT=0;
ins_loop: 
LOOP  
FETCH  c1  INTO  PIID;  
IF  at_end  <>0    THEN  
LEAVE  ins_loop;  
END  IF;  
SET PCOUNT=PCOUNT+1;
SELECT IID INTO PINT FROM YH WHERE 0=1;
END LOOP;