使用SqlServer CTE递归查询处理树、图和层次结构

cte(common table expressions)是从sql server 2005以后版本才有的。指定的临时命名结果集,这些结果集称为cte。 与派生表类似,不存储为对象,并且只在查询期间有效。与派生表的不同之处在于,cte 可自引用,还可在同一查询中引用多次。使用cte能改善代码可读性,且不损害其性能。

递归cte是sql server 2005中重要的增强之一。一般我们在处理树,图和层次结构的问题时需要用到递归查询。

cte的语法如下

 with cte as
 (
   select empid, reportto, fname from employ where empid=
   union all
   select emp.empid, emp.reportto, emp.fname from cte join employ as emp on cte.empid=emp.reportto
 )

递归cte最少包含两个查询(也被称为成员)。第一个查询为定点成员,定点成员只是一个返回有效表的查询,用于递归的基础或定位点。第二个查询被称为递归成员,使该查询称为递归成员的是对cte名称的递归引用是触发。在逻辑上可以将cte名称的内部应用理解为前一个查询的结果集。

递归查询没有显式的递归终止条件,只有当第二个递归查询返回空结果集或是超出了递归次数的最大限制时才停止递归。是指递归次数上限的方法是使用maxrecurion。

 use adventureworks;
 go
 --creates an infinite loop
 with cte (employeeid, managerid, title) as
 (
   select employeeid, managerid, title
   from humanresources.employee
   where managerid is not null
  union all
   select cte.employeeid, cte.managerid, cte.title
   from cte 
   join humanresources.employee as e 
     on cte.managerid = e.employeeid
 )
 --uses maxrecursion to limit the recursive levels to 
 select employeeid, managerid, title
 from cte
 option (maxrecursion );
 go

以上内容就是本文给大家介绍的使用sqlserver cte递归查询处理树、图和层次结构,希望大家喜欢。

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐