• sql parent_id 不定层级获取所有的子记录


    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表中的最后一层来获取下一层的数据.
  • 相关阅读:
    VueBlog
    java 代理模式
    集合框架
    面试题
    java 多线程
    网络编程
    HTTP
    MAVEN
    Redis高级
    深入浅出--梯度下降法及其实现
  • 原文地址:https://www.cnblogs.com/qianxunman/p/13341160.html
Copyright © 2020-2023  润新知