t-sql recursive query

前端 未结 5 1017
星月不相逢
星月不相逢 2021-02-06 08:03

Based on an existing table I used CTE recursive query to come up with following data. But failing to apply it a level further.

Data is as below

id    nam         


        
5条回答
  •  走了就别回头了
    2021-02-06 08:25

    Try something like this:

    WITH Recursive AS
    (
        SELECT
            ID, 
                CAST(PathName AS VARCHAR(500)) AS 'FullPaths', 
                1 AS 'Level'
        FROM 
            dbo.YourTable
        WHERE
            ParentID = 0
    
        UNION ALL
    
        SELECT
            tbl.ID, 
                CAST(r.FullPaths + '\' + tbl.PathName AS VARCHAR(500)) AS 'FullPaths', 
                r.Level + 1 AS 'Level' 
        FROM
            dbo.YourTable tbl
        INNER JOIN  
            Recursive r ON tbl.ParentID = r.ID
    )
    SELECT * FROM Recursive
    ORDER BY Level, ID
    

    Output:

    ID   FullPaths                    Level
     1   project                            1
     2   project\structure                  2
     3   project\structure\path_1           3
     4   project\structure\path_2           3
     5   project\structure\path_3           3
     6   project\structure\path_1\path_4    4
     7   project\structure\path_2\path_5    4
     8   project\structure\path_3\path_6    4
    

提交回复
热议问题