DB2存储过程中的两种指针循环方式

数据库
DB2数据中的存储过程有两种指针循环,分别是for循环和while循环。for循环比while循环简单很多,但是,有时候必须使用while循环。

DB2存储过程相信大家都比较了解了,下面为您介绍的是DB2存储过程中的两种指针循环方式,希望对您学习DB2存储过程能有所帮助。

DB2存储过程中的指针循环:

DB2存储过程有2种那个方式:for循环和while循环,如:

for循环:

  1. for c1 as select deliveryid,deliverycode from delivery where status=40 for read only do  
  2.  
  3. select sum(qty) into dQty from deliverydetail where deliveryid=c1.deliveryid;  
  4.  
  5. ......  
  6.  
  7. end for;  

while循环:

  1. declare c1 cursor for select deliveryid,deliverycode from delivery where status=40 for read only ;  
  2.  
  3. DECLARE CONTINUE HANDLER FOR NOT FOUND SET at_end_c1 = 1;  
  4.  
  5. set at_end_c1=0;  
  6. open c1 ;  
  7. FETCH c1 INTO ndeliveryid ,sdeliverycode;  
  8. WHILE ( at_end_c1 = 0) do  
  9.      select sum(qty) into dQty from deliverydetail where deliveryid=ndeliveryid ;  
  10.  
  11. ...  
  12.  
  13. set at_end_c1=0;  
  14.     FETCH c1 INTO ndeliveryid ,sdeliverycode;  
  15. END while ;  
  16. close c1;  

很明显,for循环比while循环简单很多

而且,对于while循环,如果不注意,很容易出现死循环

一般建议使用for循环.

但是,有时候必须使用while循环。

如果在循环中有事务,比如在循环中有一块要求独立事务,对于那一块,如果执行成功 ,就提交这一块,如果执行不成功,就回滚这一块,继续下一个循环,之时候就只能用while循环。

因为,当commit的时候,会自动关闭当前指针。

在while循环中,如果要commit而不关闭当前指针,要在定义指针的时候加with hold,上面的指针定义为:

  1. declare c1 cursor with hold for select deliveryid,deliverycode from delivery where status=40 for read only ; 

对于for循环是没有办法处理的。

如果需要用rollback,需要定义savepoint,然后回滚到指定的回滚点。
 

 

 

 

【编辑推荐】

DB2创建数据库的实现

DB2目录视图说明

DB2数据库命令大全

DB2装入命令的性能因素

DB2列转行的实现

责任编辑:段燃 来源: 互联网
相关推荐

2010-08-31 17:14:24

DB2表空间

2010-11-04 10:16:38

db2日志保存

2010-08-26 15:15:18

DB2备份

2010-08-31 15:39:25

DB2存储过程

2010-08-05 14:24:37

DB2存储过程

2010-11-03 10:35:45

DB2存储过程

2010-11-02 10:27:38

DB2分区数据库恢复

2010-09-07 09:43:34

DB2提供

2010-08-02 13:05:01

DB2应用

2010-11-01 09:54:24

DB2管理服务器

2010-07-27 13:46:08

DB2提高IMPORT

2010-08-18 13:29:11

DB2存储过程

2010-11-03 10:46:49

DB2存储过程

2010-11-03 10:26:22

DB2存储过程

2010-08-05 10:42:33

DB2 拉链表存储过程

2010-08-10 13:36:00

2010-11-04 13:58:58

DB2存储过程

2010-08-10 15:30:21

2018-02-01 08:25:10

DB2存储方法

2010-11-04 09:31:21

DB2循环语句
点赞
收藏

51CTO技术栈公众号