SQL Server 递归

SQL Server 没有类似于Oracle START WITH NAME='xx' CONNECT BY PRIOR ID=PARENT_ID这样的语句,但是可以通过自定义标准函数+With语句实现,速度也是杠杠的

ALTER FUNCTION  [dbo].[RecursionSysLocation]
(    
    -- Add the parameters for the function here
    @ParentId nvarchar(36)
)
RETURNS TABLE 
AS
RETURN 
(
    with temp ( [Id], [parentid])
    as
    (
        select Id, ParentId
        from SysLocation
        where ParentId = @ParentId
        union all
        select a.Id, a.ParentId
        from SysLocation a
        inner join temp on a.ParentId = temp.[Id]        
    )
    
    select s.Id, s.ParentId from SysLocation s where Id=@ParentId
    union all
    select * from temp
)
原文地址:https://www.cnblogs.com/lcy1984/p/5569369.html