SQL Server Recursive CTE
SQL Server Recursive CTE
Summary: in this tutorial, you will learn how to use the SQL Server
recursive CTE to query hierarchical data.
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.
In this example:
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;
Here is the output:
In this example, the anchor member gets the top manager and the
recursive query returns subordinates of the top managers and
subordinates of the top manager, and so on.
In this tutorial, you have learned how to use the SQL Server recursive
CTE to query hierarchical data.