存储过程构建递归树.


    
  --示例数据  
  create   table   tb(子结点   int,父结点   int,名称   varchar(20))  
  insert   tb   select   1,0,'父结点名称1'  
  union   all   select   2,1,'子结点名称'  
  union   all   select   3,2,'子结点名称'  
  union   all   select   4,2,'子结点名称'  
  union   all   select   5,1,'子结点名称'  
  union   all   select   6,1,'子结点名称'  
  union   all   select   7,1,'子结点名称'  
  union   all   select   8,7,'子结点名称'  
  union   all   select   9,7,'子结点名称'  
  go  
   
  --查询处理的函数  
  create   function   f_id(  
  )returns   @re   table(id   int,level   int,sid   varchar(8000))  
  as  
  begin  
  declare   @l   int  
  set   @l=0  
  insert   @re   select   子结点,@l,right(10000+子结点,4)  
  from   tb   where   父结点=0  
  while   @@rowcount>0  
  begin  
  set   @l=@l+1  
  insert   @re   select   a.子结点,@l,b.sid+right(10000+a.子结点,4)  
  from   tb   a,@re   b  
  where   a.父结点=b.id   and   b.level=@l-1  
  end  
  return  
  end  
  go  
   
  --调用(查询所有的子)  
  select   结果=space(b.level   *4)+a.名称  
  from   tb   a,f_id()   b   where   a.子结点=b.id  
  order   by   b.sid  
  go  
   
  --删除测试  
  drop   table   tb  
  drop   function   f_id  
   
  /*--测试结果  
   
  结果                                            
  -------------------------  
  父结点名称1  
          子结点名称  
                  子结点名称  
                  子结点名称  
          子结点名称  
          子结点名称  
          子结点名称  
                  子结点名称  
                  子结点名称  
   
  (所影响的行数为   9   行)  
  --*/ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值