TSQL递归CTE线程排序

时间:2010-11-12 08:41:24

标签: tsql

我有下表:

ID parentID   name

1  0          car1
2  1          tire
3  2          rubber
4  0          car2
5  2          nut
6  3          black

帮助测试...

CREATE TABLE #TT (ID int
                 ,ParentID int
                 ,Name varchar(25)
                 )

INSERT #TT 
SELECT 1,0,'car1' UNION ALL
SELECT 2,1,'tire' UNION ALL
SELECT 3,2,'rubber' UNION ALL
SELECT 4,0,'car2' UNION ALL
SELECT 5,2,'nut' UNION ALL
SELECT 6,3,'black'

我正在尝试创建一个“线程”层次结构,但我想列出父节点下的子节点,如下所示:

ID parentID   name

1  0          car1
2  1          tire
3  2          rubber
6  3          black
5  2          nut
4  0          car2

如果我使用像这样的递归CTE ......

;WITH Features
AS
(
    SELECT *
    FROM #TT
    WHERE ParentID = 0

    UNION ALL

    SELECT F.*
    FROM #TT AS F
        INNER JOIN Features
            ON F.ParentID = Features.ID
)

SELECT *
FROM Features

我最终得到了这个......

ID parentID   name

1  0          car1
4  0          car2
2  1          tire
3  2          rubber
5  2          nut
6  3          black

任何想法?提前谢谢。

2 个答案:

答案 0 :(得分:3)

您可以随身携带构建树路径,并按照

进行排序

这样的东西
DECLARE @TT TABLE(ID int, ParentID int, Name varchar(25)) 

INSERT @TT  
SELECT 1,0,'car1' UNION ALL 
SELECT 2,1,'tire' UNION ALL 
SELECT 3,2,'rubber' UNION ALL 
SELECT 4,0,'car2' UNION ALL 
SELECT 5,2,'nut' UNION ALL 
SELECT 6,3,'black' 


SELECT  *
FROM    @TT


;WITH Features AS (
        SELECT  *,
                CAST(ID AS VARCHAR(MAX))  + '/' AS TreePath
        FROM    @TT
        WHERE   ParentID = 0
        UNION ALL
        SELECT  tt.*,
                f.TreePath + CAST(tt.ID AS VARCHAR(10)) + '/'
        FROM    @TT tt INNER JOIN
                Features f  ON  tt.ParentID = f.ID
)
SELECT  *
FROM    Features
ORDER BY TreePath

答案 1 :(得分:0)

尝试添加ORDER BY子句,例如:

SELECT * FROM Features 
ORDER BY parentID