Common Table Expressions (CTEs) are handy when writing recursive queries in
SQL Server. They let you create a temporary result set that can reference itself, which helps in working with hierarchical data like employee-manager relationships or folder structures. A recursive CTE has two main parts: 1. **Anchor member** – this part gets the initial set of rows. 2. **Recursive member** – this part references the CTE itself to get the next level of data. You put these parts together with a UNION ALL, and SQL Server will keep running the recursive member until it can’t find any new rows. This builds up the full result set step by step. Using a CTE, you can easily pull the entire employee hierarchy, starting from the top manager all the way down. CTEs make things simpler than trying to write complicated code or using several joins, making recursive queries more straightforward and easier to work with.
WITH EmployeeHierarchy AS (
SELECT EmployeeID, ManagerID, Name
FROM Employees
WHERE ManagerID IS NULL -- Anchor member (top-level manager)
UNION ALL
SELECT e.EmployeeID, e.ManagerID, e.Name
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID -- Recursive member
)
SELECT * FROM EmployeeHierarchy;
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Common Table Expressions (CTEs) are handy when writing recursive queries in SQL Server. They let you create a temporary result set that can reference itself, which helps in working with hierarchical data like employee-manager relationships or folder structures. A recursive CTE has two main parts: 1. **Anchor member** – this part gets the initial set of rows. 2. **Recursive member** – this part references the CTE itself to get the next level of data. You put these parts together with a UNION ALL, and SQL Server will keep running the recursive member until it can’t find any new rows. This builds up the full result set step by step. Using a CTE, you can easily pull the entire employee hierarchy, starting from the top manager all the way down. CTEs make things simpler than trying to write complicated code or using several joins, making recursive queries more straightforward and easier to work with.