存储过程构建递归树.

来源:互联网 发布:otg软件 编辑:程序博客网 时间:2024/06/05 19:06


    
  --示例数据  
  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   行)  
  --*/ 

原创粉丝点击