A common table expression (CTE) is a named temporary result set referenced within a query. A recursive CTE can reference itself, making hierarchical queries practical without cursors. section 3.3
Build a recursive hierarchy query from two parts:
- Start with an anchor query, such as Sanjay Gupta’s employee record. section 3.3
- Use UNION ALL to join employees to the CTE’s previous results through EmployeeID and ManagerID. section 3.3
- Query the completed CTE and join back to Employees when manager details are needed. section 3.3
Reporting all direct and indirect employees
EmployeeCTE begins with EmployeeID 2, repeatedly finds employees whose ManagerID matches a prior result, and returns the resulting hierarchy. Guard recursive queries: an error can create an infinite loop; recursion defaults to 100 levels and can be overridden with MAXRECURSION. section 3.3
Figure 3.2 MagicChoc management org chart
Use the organizational chart to visualize the manager-child relationships traversed by the recursive query. section 3.3





