sql >> Base de Datos >  >> RDS >> Sqlserver

Seleccionar padre e hijo de la misma tabla

Debe usar una CTE recursiva (expresión de tabla común) para esto:

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