SQL Server Recursive CTE

Summary: in this tutorial, you will learn how to use the SQL Server recursive CTE to query hierarchical data.

Introduction to 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.

The following shows the syntax of a recursive CTE:

 

WITH expression_name (column_list) AS ( -- Anchor member initial_query UNION ALL -- Recursive member that references expression_name. recursive_query ) -- references expression name SELECT * FROM expression_name

Code language: SQL (Structured Query Language) (sql)

In general, a recursive CTE has three parts:

  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.

The execution order of a recursive CTE is as follows:

  • 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.

The following flowchart illustrates the execution of a recursive CTE:

 

SQL Server Recursive CTE examples

Let’s take some examples of using recursive CTEs

A) Simple SQL Server recursive CTE example

This example uses a recursive CTE to returns weekdays from Monday to Saturday:

WITH cte_numbers(n, weekday) 
AS (
    SELECT 
        0, 
        DATENAME(DW, 0)
    UNION ALL
    SELECT    
        n + 1, 
        DATENAME(DW, n + 1)
    FROM    
        cte_numbers
    WHERE n < 6
)
SELECT 
    weekday
FROM 
    cte_numbers;

Here is the result set:

In this example:

The DATENAME() function returns the name of the weekday based on a weekday number.

The anchor member returns the Monday

SELECT 
    0, 
    DATENAME(DW, 0)

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

B) Using a SQL Server recursive CTE to query hierarchical data

See the following sales.staffs table from the sample database:

 

In this table, a staff reports to zero or one manager. A manager may have zero or more staffs. The top manager has no manager. The relationship is specified in the values of the manager_id column. If a staff does not report to any staff (in case of the top manager), the value in the manager_id is NULL.

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;

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WITH RECURSIVESQL Server中递归查询的一种方式,也称为CTE递归查询。递归查询是指在一个表中对自身进行查询,直到查询结果满足条件为止。在SQL Server中使用WITH RECURSIVE可以实现递归查询。WITH RECURSIVE的语法如下: ``` WITH recursive_cte (col1, col2, col3, ...) AS ( --初始查询语句 SELECT col1, col2, col3, ... FROM table_name WHERE condition UNION ALL --递归查询语句 SELECT col1, col2, col3, ... FROM table_name JOIN recursive_cte ON recursive_cte.col = table_name.col WHERE condition ) SELECT * FROM recursive_cte; ``` 其中,recursive_cte是递归公共表达式的名称,col1、col2、col3是要查询的列,table_name是要查询的表名,condition是查询条件。在WITH RECURSIVE中,包含两个查询语句:初始查询语句和递归查询语句。初始查询语句用于筛选出符合条件的记录,递归查询语句用于在初始查询语句的基础上对自身进行递归查询。 需要注意的是,WITH RECURSIVE中的递归查询语句必须包含UNION ALL关键字,并且UNION ALL后面的SELECT语句必须引用了递归公共表达式recursive_cte。如果不包含UNION ALL或者引用了其他表,则会导致死循环。 以下是一个WITH RECURSIVE的例子: ``` WITH recursive_cte (employee_id, manager_id, level) AS ( -- 初始查询语句 SELECT employee_id, manager_id, 0 as level FROM employee_table WHERE employee_id = 1 UNION ALL -- 递归查询语句 SELECT employee_table.employee_id, employee_table.manager_id, recursive_cte.level + 1 FROM employee_table JOIN recursive_cte ON recursive_cte.manager_id = employee_table.employee_id ) SELECT * FROM recursive_cte; ``` 这个例子用于查询一个员工及其直接或间接的所有上级领导。在初始查询语句中,我们选择了员工ID为1的员工作为起点。在递归查询语句中,我们通过JOIN连接到employee_table表中,并使用recursive_cte中的level来计算每个员工的级别。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值