Hierarchical and Recursive Queries in SQL Server
Jasmin Ludolf
Content Developer
What is recursion?
Recursion is the use of a procedure, subroutine, function, or algorithm that calls itself one or more times until a specified condition is met
Definition of a Common Table Expression (CTE):
WITH CTEtable as (
<select statement on a table>
)
SELECT *
FROM CTEtable
Specifies a temporary named result set, known as a common table expression (CTE)
Definition of a recursive CTE:
WITH cte_name AS (
-- Anchor member
<cte_initial_query>
UNION ALL
-- Recursive member
<cte_recursive_query> )
SELECT *
FROM cte_name
Real-world examples:
Manipulating a table:
CREATE
, INSERT
, ALTER
, DROP
Relational data model:
Hierarchical and networked data model:
Common tasks:
Travel planning of flight data:
How to assemble a car?
Modeling a power grid
Hierarchical and Recursive Queries in SQL Server