db2数据库存储过程入门6

例8:

--在存储过程中用while循环进行递归查找sid分类下的所有子分类
drop procedure test14;
create procedure test14(in sid integer)
language sql
begin

 declare num        integer;--子分类的数量
 declare global temporary table session.c_dtdoctype--子分类的临时表
 (
  id integer,
  parentid integer,
  name varchar(300)
 );
 declare global temporary table session.p_dtdoctype--父分类的临时表
 (
  id integer,
  parentid integer,
  name varchar(300)
 );
 declare global temporary table session.r_dtdoctype--结果分类的临时表
 (
  id integer,
  parentid integer,
  name varchar(300)
 )with replace;
 --查询表dtdoctype中的数据,插入到临时表session.dtdoctype中
 insert into session.p_dtdoctype select id,parentid,name from dtdoctype where parentid = sid;
 insert into session.r_dtdoctype select id,parentid,name from dtdoctype where parentid = sid;
 select count(*) into num from session.p_dtdoctype;--查询父表中是否有数据
 
 while(num>0)
 do
  delete from session.c_dtdoctype;--删除子表中的数据
  --从父表中查出子分类集合存放到子表中
  insert into session.c_dtdoctype select id,parentid,name from dtdoctype where parentid in (select id from session.p_dtdoctype);
  insert into session.r_dtdoctype select id,parentid,name from dtdoctype where parentid in (select id from session.p_dtdoctype);
  --从父表中查出子分类集合存放到子表中
  delete from session.p_dtdoctype;--删除父表中的数据
  --将子表中的数据存放在父表中
  insert into session.p_dtdoctype select * from session.c_dtdoctype;
  --查询父表中是否有数据
  select count(*) into num from session.p_dtdoctype;
  
 end while;
 
 begin
  declare Ydtdoctype cursor with return for select * from session.r_dtdoctype;
  open Ydtdoctype;--打开游标
 end;
 
 drop table session.c_dtdoctype;
 drop table session.p_dtdoctype;
 --drop table session.r_dtdoctype;
end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值