[SQL]網路上看到的好屌的遞迴Recursive查詢

  • 7443
  • 0

摘要:[SQL]網路上看到的好屌的遞迴Recursive查詢


WITH EmpChart AS
(
SELECT EmployeeId, ReportsTo, 1 AS treelevel
FROM Employees
WHERE (Employees.ReportsTo = 2)
UNION ALL
SELECT e.EmployeeId, e.ReportsTo, treelevel +1
FROM Employees e
JOIN EmpChart ec
ON e.ReportsTo=ec.EmployeeID
)
SELECT * FROM EmpChart;

像是這個可以一層一層的從老闆最高層到最底層的員工ID通通遞迴查詢出來

好屌

Spool operators in query plan...

看到的