Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Wählen Sie Eltern und Kind aus derselben Tabelle aus

Hierfür sollten Sie einen rekursiven CTE (Common Table Expression) verwenden:

-- 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