Bạn nên sử dụng CTE đệ quy (Biểu thức bảng chung) cho việc này:
-- 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