首页 > 技术文章 > sql parent_id 不定层级获取所有的子记录

qianxunman 2020-07-19 20:47 原文

https://www.cnblogs.com/JiangXiaoTian/articles/3670144.html

--调用方法:  
--select * from GetChild('24')  
--select id from GetChild('24')  
--select * from KuCun where ProductType in(select id from GetChild('24'))  
  
Create function [dbo].[GetChild](@ID varchar(10))  
returns @t table(ID varchar(10),ParentID varchar(10),Level int)  
as  
begin  
    declare @i int  
    set @i = 1  
    insert into @t select @ID,@ID,0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作  
    insert into @t select ID,ParentID,@i from Dept where ParentID = @ID  
  
    while @@rowcount<>0  
    begin  
        set @i = @i + 1  
        insert into @t  
        select  
            a.ID,a.ParentID,@i  
        from  
            Dept a,@t b  
        where  
            a.ParentID=b.ID and b.Level = @i-1  
    end  
    return  
end  

说明:

  • 函数巧妙使用了一个层级字段level 来标记每次插入的数据是第几层的,然后循环使用@t表中的最后一层来获取下一层的数据.

推荐阅读