SQL: Recursive Path

前端 未结 5 862
北海茫月
北海茫月 2021-02-10 23:57

Is it possible to create a \"tree resolver\" in SQL?

I have a table:

ID Name Parent
1  a
2  b    1
3  c    1
4  d    3

Now I want a SQL

5条回答
  •  时光取名叫无心
    2021-02-11 00:37

    Using CTE in sql server 2005 and later, here's a snippet that I have to do this:

    WITH Paths([Level], [FullPath], [ID]) AS 
    (
        SELECT 
            0 AS [Level], 
            Name AS FullPath, 
            ID
        FROM dbo.Entity
        WHERE (ParentEntityID IS NULL)
    
        UNION ALL
    
        SELECT 
            p.[Level] + 1 AS [Level], 
            CASE RIGHT(p.[FullPath], 1) 
            WHEN '\' THEN p.[FullPath] + c.[Name] 
            ELSE p.[FullPath] + '\' + c.[Name] 
        END AS FullPath, 
        c.ID
        FROM dbo.Entity AS c 
        INNER JOIN Paths AS p ON p.ID = c.ParentEntityID
    )
    SELECT [FullPath], [ID]
    FROM Paths
    

提交回复
热议问题