SQL-自定义函数方式实现父节点查询子节点

交谈中请勿轻信汇款、中奖信息、陌生电话,勿使用外挂软件。

许志鹏  12:23:17
if OBJECT_ID('tb','U') is not null drop table tb  
go  
create table tb(ID int,PID INT)  
insert into tb  
select 1,0 union all  
select 2,1 union all  
select 3,2 union all  
select 4,3 union ALL  
select 5,4 union ALL  
select 6,5 union ALL  
select 7,6   
--自定义函数方式实现父节点查询子节点  
if OBJECT_ID('GetChildID') is not null drop function GetChildID  
go  
create function GetChildID(@ParentID int)  
returns @t table(ID int)  
as  
  begin  
     insert into @t select ID from tb where PID=@ParentID  
     while @@rowcount<>0  
     begin  
        insert into @t select a.ID from tb as a   
        inner join @t as b  
        on a.PID=b.ID  
        and not exists(select 1 from @t where ID=a.ID)  
     end  
     return   
  end  
go  
select * from dbo.GetChildID(1)  

  

posted on 2013-03-14 14:17  pass  阅读(206)  评论(0)    收藏  举报

导航