Recursive CTE in SQL Server
Recursive CTE in SQL Server
https://www.sqlservertutorial.net/sql-server-basics/sql-server-recursive-cte/
A recursive common table expression (CTE) is a CTE that references itself. By doing so, the CTE repeatedly executes, returns subsets of data,
until it returns the complete result set.
A recursive CTE is useful in querying hierarchical data such as organization charts where one employee reports to a manager or multi-level
bill of materials when a product consists of many components, and each component itself also consists of many other components.
1. An initial query that returns the base result set of the CTE. The initial query is called an anchor member.
2. A recursive query that references the common table expression, therefore, it is called the recursive member. The recursive member
is union-ed with the anchor member using the UNION ALL operator.
3. A termination condition specified in the recursive member that terminates the execution of the recursive member.
First, execute the anchor member to form the base result set (R0), use this result for the next iteration.
Second, execute the recursive member with the input result set from the previous iteration (Ri-1) and return a sub-result set (Ri)
until the termination condition is met.
Third, combine all result sets R0, R1, … Rn using UNION ALL operator to produce the final result set.
SELECT
0,
DATENAME(DW, 0)
Code language: SQL (Structured Query Language) (sql)
The recursive member returns the next day starting from the Tuesday till Sunday.
SELECT
n + 1,
DATENAME(DW, n + 1)
FROM
cte_numbers
WHERE n < 6
The condition in the WHERE clause is the termination condition that stops the execution of the recursive member when n is 6
n<6
Code language: SQL (Structured Query Language) (sql)
This example uses a recursive CTE to get all subordinates of the top manager who does not have a manager (or the value in
the manager_id column is NULL):
WITH cte_org AS (
SELECT
staff_id,
first_name,
manager_id
FROM
sales.staffs
WHERE manager_id IS NULL
UNION ALL
SELECT
e.staff_id,
e.first_name,
e.manager_id
FROM
sales.staffs e
INNER JOIN cte_org o
ON o.staff_id = e.manager_id
)
SELECT * FROM cte_org;