如何使用SQL CTE获取完整的层次结构

时间:2011-12-13 03:09:07

标签: sql sql-server-2008 recursive-query

您好我正在尝试获取我的类别的完整层次结构。这是我的样本表

ID     PARENT_ID       NAME          DEPTH
------------------------------------------
1      NULL            A             1
2      NULL            B             1
3      NULL            C             1
4      1               D             2
5      4               E             3

cte输出应为此

ID     PARENT_ID       NAME
---------------------------
1      NULL            A             
2      NULL            B             
3      NULL            C             
4      1               D             
5      4               E             
5      1               E  

正如您所见,id:5是4和1的父级。如何查询整个树

3 个答案:

答案 0 :(得分:2)

DECLARE @tmp TABLE(ID INT,ParentID INT,NAME VARCHAR(10),DEPTH INT)

INSERT INTO @tmp VALUES
(1      ,NULL            ,'A'             ,1 ),
(2      ,NULL            ,'B'             ,1 ),
(3      ,NULL            ,'C'             ,1 ),
(4      ,1               ,'D'             ,2 ),
(5      ,4               ,'E'            ,3 ),
(6      ,5               ,'F'            ,4 );

select * from @tmp

;WITH cte AS
(
    SELECT   A.ID
            ,A.ParentID
            ,A.NAME
            ,A.DEPTH
    FROM    @tmp A

    UNION ALL

    SELECT   A.ID
            ,B.ParentID
            ,A.NAME
            ,A.DEPTH 
    FROM    cte A 
    INNER JOIN @tmp B on A.ParentID = B.ID 
    WHERE   B.ParentID IS NOT NULL

)

SELECT * FROM cte

答案 1 :(得分:1)

在SQL Server 2008中,CTE可用于递归查询。

来自MSDN

的CTE示例

- 样品溶液(未经测试)

;With TableCTE(Id, Name, ParentId, Depth)
(
   Select ID,Name,ParentId, 1
     FROM MyTable

   Union All

   Select C.Id, C.Name, t.ParentId, c.Depth +1
     FROM @tmp t
    INNER JOIN TableCTE C on t.Id = c.ParentId
    -- Where t.ParentId IS Not Null
)

SELECT Id, Name, ParentId
FROM TableCTE

答案 2 :(得分:0)

;WITH cte AS
(
    SELECT   A.ID
            ,A.ParentID
            ,A.NAME
            ,A.DEPTH
    FROM    @tmp A
    WHERE   A.ParentID IS NULL

    UNION ALL

    SELECT   B.ID
            ,B.ParentID
            ,B.NAME
            ,B.DEPTH 
    FROM    cte A 
              INNER JOIN 
            @tmp B on B.ParentID = A.ID
    WHERE   B.ParentID IS NOT NULL

)

SELECT * FROM cte