DB2编程序的技巧之游标的正确使用


  本文标签:DB2编程序

  我们今天主要向大家讲述的是DB2编程序的小技巧之游标的使用,如果你对DB2编程序的小技巧之游标的使用有兴趣的话,你就可以对以下的文章点击观看了,以下就是文章的主要内容的详细描述,望大家在浏览之后会对其有更深的了解  。

  注意commit和rollback

  使用游标时要特别注意如果没有加with hold 选项,在Commit和Rollback时,该游标将被关闭  。Commit 和Rollback有很多东西要注意  。特别小心

  游标的两种定义方式

  一种为

  1. declare continue handler for not found  
  2. begin  
  3. set v_notfound = 1;  
  4. end;  
  5. declare cursor1 cursor with hold for select market_code from tb_market_code for update;  
  6. open cursor1;  
  7. set v_notfound=0;  
  8. fetch cursor1 into v_market_code;  
  9. while v_notfound=0 Do  
  10. --work  
  11. set v_notfound=0;  
  12. fetch cursor1 into v_market_code;  
  13. end while;  
  14. close cursor1;  

  这种方式使用起来比较复杂,但也比较灵活  。特别是可以使用with hold 选项  。如果循环内有commit或rollback 而要保持该cursor不被关闭,只能使用这种方式  。

  另一种为

  1. pcursor1: for loopcs1 as cousor1 cursor as  
  2. select market_code as market_code  
  3. from tb_market_code  
  4. for update  
  5. do  
  6. end for;  

  这种方式的优点是比较简单,不用(也不允许)使用open,fetch,close  。

  但不能使用with hold 选项  。如果在游标循环内要使用commit,rollback则不能使用这种方式  。如果没有commit或rollback的要求,推荐使用这种方式(看来For这种方式有问题)  。

  修改游标的当前记录的方法

  1. update tb_market_code set market_code=0 where current of cursor1; 

  不过要注意将cursor1定义为可修改的游标

  1. declare cursor1 cursor for select market_code from tb_market_code  
  2. for update;  

  for update 不能和GROUP BY、 DISTINCT、 ORDER BY、 FOR READ ONLY及UNION, EXCEPT, or INTERSECT但 UNION ALL除外)一起使用  。

DB2编程序的小技巧之游标的使用

  

  上述的相关内容就是对DB2编程序的小技巧之游标的使用的描述,希望会给你带来一些帮助在此方面  。