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

Selecione pai e filho da mesma tabela


Você deve usar um CTE recursivo (Common Table Expression) para isso:
-- define the recursive CTE and give it a name
;WITH Hierarchy AS
(
    -- "anchor" - top-level rows to select, here those with ManagerId = 0
    SELECT EmpId, EmpName, NULL AS 'MgrId', CAST(NULL AS NVARCHAR(50)) AS 'MgrName', 1 AS 'Level'
    FROM dbo.Emp
    WHERE ManagerId = 0

    UNION ALL

    -- recursive part - join an employee to its manager via ManagerId -> mgr.EmpId
    SELECT e.EmpId, e.EmpName, mgr.EmpId, mgr.EmpName, mgr.Level + 1 AS 'Level'
    FROM dbo.Emp e
    INNER JOIN Hierarchy mgr ON e.ManagerId = mgr.EmpId
)
SELECT * FROM Hierarchy