db2数据库存储过程入门4

本文介绍了DB2存储过程中如何声明变量、创建和使用临时表以及简单游标。通过示例展示了在存储过程中创建带有WITH REPLACE选项的全局临时表,以及如何在游标中返回结果集。在实践中应注意存储过程结束前不应删除临时表,以免影响后续操作。

例6:

--在存储过程中声明变量
--在存储过程中建立临时表
--在存储过程中使用简单游标
create procedure test11(in sid integer)
language sql
begin

 declare a integer;
 declare global temporary table session.dtdoctype
 (
  id integer,
  parentid integer,
  name varchar(300)
 );
 
 --查询表dtdoctype中的数据,插入到临时表session.dtdoctype中
 insert into session.dtdoctype select id,parentid,name from dtdoctype where parentid = sid;
 
 begin
  --将临时表session.dtdoctype中的所有数据存到游标Ydtdoctype中
  --with return将结果集返回
  declare Ydtdoctype cursor with return for select * from session.dtdoctype;
  
  open Ydtdoctype;--打开游标
 
 end;
 drop table session.dtdoctype;
end;
解释:通过call test(1)在数据库做来调用存储过程 ,会出现:
SQL0910N  SQL 语句不能访问在其上的修改被暂挂的对象。  SQLSTATE=57007
原因是在存储过程关闭前进行了drop table session.dtdoctype,所有查询不到。
 要是注释了drop table session.dtdoctype;则第二次会话就会报错:
要创建的对象名称与类型为"declare global temporary" 的现有"session.dtdoctype"相同
------------------------------------------------------------------
如果想避免创建临时表时出现:对象名称与类型为"declare global temporary" 的现有"session.dtdoctype"相同
则可以替换原来的临时表,实例如下:

create procedure test12(in sid integer)
language sql
begin

 declare a integer;
 declare global temporary table session.dtdoctype
 (
  id integer,
  parentid integer,
  name varchar(300)
 )with replace;
 
 
 --查询表dtdoctype中的数据,插入到临时表session.dtdoctype中
 insert into session.dtdoctype select id,parentid,name from dtdoctype where parentid = sid;
 
 begin
  --将临时表session.dtdoctype中的所有数据存到游标Ydtdoctype中
  --with return将结果集返回
  declare Ydtdoctype cursor with return for select id,parentid,name from dtdoctype where id in( select id from session.dtdoctype);
  
  open Ydtdoctype;--打开游标
 
 end;

end;

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值