Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Como obter a hierarquia completa com SQL CTE

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