---
title: "DB2 中游标的使用以及 存储过程的写法"
author: "lumans"
date: "2009-11-21T22:39:01Z"
tags: []
slug: "db2"
draft: false
lastmod: "2009-11-21T22:39:01Z"
id: 522406
url: "https://lumans.iteye.com/blog/522406"
---

from:http://j2megame.bokee.com/4020626.html

DB2 中游标的使用以及 存储过程的写法

问题1：  
什么时候才会发生not found异常 ，以及db2中sqlcode的值是如何变化的？  
    在db2中，一条select 语句也有可能发生not found异常，譬如  
declare sqlcode integer default 0;  
declare sql\_code integer default 0;  
declare classCode varchar(40) ;  
select app\_class\_code into classCode from kf\_app\_class where app\_name='无效记录';  
set sql\_code=sqlcode;  
如果此时没有检索到记录，那么sqlcode的值为100，有的话为0;  
我们可以定义NOT FOUND 异常处理

declare sqlcode integer default 0;  
declare sql\_code integer default 0;  
declare classCode varchar(40) ;  
begin  
declare continue handler for not found  
begin  
\--注如果发生not found那么此时的sqlcode必定为100  
set sql\_code=sqlcode;/\*在这里sqlcode的值为100；\*/  
\--如果再次得到sqlcode的值那么它的值变为0  
set sql\_code=sqlcode;/\*这里sqlcode变成了0，因为上一条语句执行成功了，那么sqlcode变成了0\*/  
end;  
select app\_class\_code into classCode from kf\_app\_class where app\_name='无效记录';  
set sql\_code=sqlcode;/\*同理此时如果没有取到数据，那么会进declare continue handler ，返回后sqlcode的值也为0\*/  
end;  
所以我们可以通过两种方法来捕获和处理not found  
方法1：

begin  
declare continue handler for not found  
begin  
     --异常处理代码  
end;  
sql语句  
end;  
方法2：

begin

sql语句  
if sqlcode=100 then  
\--异常处理代码  
end if;  
end;  
问题2：  
定义了游标，怎么fecth一条记录，怎么进行循环？  
Q:定义了游标假设发生not found 异常，那么是在open cursorName的时候还是在fecth的时候发生异常？  
A：检验游标中的数据是否取完或者有无记录，应该在fecth的时候，而不是发生在open cursorName的时候，  
下面一个例子详细的说明了游标使用过程

begin  
declare sqlcode integer default 0;  
declare app\_code varchar(10);  
declare cursor1 cursor for select app\_code from kf\_app\_class ;  
open cursor1;  
cursorLoop:  
loop  
     fecth cursor1 into app\_code ;  
     if sqlcode=100 then leave cursorLoop;  
     end if;  
end loop;  
end;

Q:sqlcode 可以直接用吗？  
A:在db2中，如果要使用sqlcode那么必须在使用前declare;  
譬如  
declare sqlcode integer default 0;  
if sqlcode =? then  
end if;  
附注  
db2的其他异常处理

对应 oracle的 when other exceptions

declare exit handler for sqlwaring,sqlexcption  
begin  
－－处理异常  
end;

当程序执行exit handler异常处理后，那么会退出程序，不会在接着执行，也就是

declare exit handler for sqlwaring,sqlexcption  
begin  
－－处理异常  
end;  
sql语句1；  
sql语句2；  
执行sql语句1发生异常，会进入 exit handler ，然后退出程序，不会在执行 sql语句2