WITH DepartmentCTE AS ( SELECT DepartmentID, EmployeeName FROM Employees WHERE DepartmentID =1 ) SELECT* FROM DepartmentCTE;
CTE的應用場景
簡化複雜查詢 CTE可以用來分解複雜的查詢,使其更易於理解和維護。例如:
1 2 3 4 5 6 7 8 9
WITH SalesCTE AS ( SELECT SalesPerson, SUM(SalesAmount) AS TotalSales FROM Sales GROUPBY SalesPerson ) SELECT* FROM SalesCTE WHERE TotalSales >10000;
逐層遞迴 CTE在處理遞迴查詢時非常有用,例如處理組織結構或分層數據:
1 2 3 4 5 6 7 8 9 10 11 12 13
sql 複製程式碼 WITH HierarchyCTE AS ( SELECT EmployeeID, ManagerID, EmployeeName FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.ManagerID, e.EmployeeName FROM Employees e INNER JOIN HierarchyCTE h ON e.ManagerID = h.EmployeeID ) SELECT * FROM HierarchyCTE;
WITH RecursiveCTE AS ( -- 基準成員 SELECT ... FROM ... WHERE ... UNIONALL -- 遞迴成員 SELECT ... FROM ... INNERJOIN RecursiveCTE ... ) SELECT*FROM RecursiveCTE;
遞迴CTE範例 以下是一個處理員工層次結構的範例:
1 2 3 4 5 6 7 8 9 10 11
WITH HierarchyCTE AS ( SELECT EmployeeID, ManagerID, EmployeeName FROM Employees WHERE ManagerID ISNULL UNIONALL SELECT e.EmployeeID, e.ManagerID, e.EmployeeName FROM Employees e INNERJOIN HierarchyCTE h ON e.ManagerID = h.EmployeeID ) SELECT*FROM HierarchyCTE;
CTE的性能考量
CTE vs 臨時表 CTE是為了可讀性而設計的,但在某些情況下,使用臨時表可能會有更好的性能。需要根據具體情況進行性能測試。