递归CTE是SQL SERVER 2005中重要的增强之一。一般我们在处理树,图和层次结构的问题时需要用到递归查询。
CTE的语法如下
1 WITH CTE AS
2 (
3 SELECT EmpId, ReportTo, FName FROM Employ WHERE EmpId=1
4 UNION ALL
5 SELECT emp.EmpId, emp.ReportTo, emp.FName FROM CTE JOIN Employ as emp ON CTE.EmpId=emp.ReportTo
6 )
2 (
3 SELECT EmpId, ReportTo, FName FROM Employ WHERE EmpId=1
4 UNION ALL
5 SELECT emp.EmpId, emp.ReportTo, emp.FName FROM CTE JOIN Employ as emp ON CTE.EmpId=emp.ReportTo
6 )
递 归CTE最少包含两个查询(也被称为成员)。第一个查询为定点成员,定点成员只是一个返回有效表的查询,用于递归的基础或定位点。第二个查询被称为递归成 员,使该查询称为递归成员的是对CTE名称的递归引用是触发。在逻辑上可以将CTE名称的内部应用理解为前一个查询的结果集。
递归查询没有显式的递归终止条件,只有当第二个递归查询返回空结果集或是超出了递归次数的最大限制时才停止递归。是指递归次数上限的方法是使用MAXRECURION。
1 USE AdventureWorks;
2 GO
3 --Creates an infinite loop
4 WITH cte (EmployeeID, ManagerID, Title) as
5 (
6 SELECT EmployeeID, ManagerID, Title
7 FROM HumanResources.Employee
8 WHERE ManagerID IS NOT NULL
9 UNION ALL
10 SELECT cte.EmployeeID, cte.ManagerID, cte.Title
11 FROM cte
12 JOIN HumanResources.Employee AS e
13 ON cte.ManagerID = e.EmployeeID
14 )
15 --Uses MAXRECURSION to limit the recursive levels to 2
16 SELECT EmployeeID, ManagerID, Title
17 FROM cte
18 OPTION (MAXRECURSION 2);
19 GO
2 GO
3 --Creates an infinite loop
4 WITH cte (EmployeeID, ManagerID, Title) as
5 (
6 SELECT EmployeeID, ManagerID, Title
7 FROM HumanResources.Employee
8 WHERE ManagerID IS NOT NULL
9 UNION ALL
10 SELECT cte.EmployeeID, cte.ManagerID, cte.Title
11 FROM cte
12 JOIN HumanResources.Employee AS e
13 ON cte.ManagerID = e.EmployeeID
14 )
15 --Uses MAXRECURSION to limit the recursive levels to 2
16 SELECT EmployeeID, ManagerID, Title
17 FROM cte
18 OPTION (MAXRECURSION 2);
19 GO
本文转自齐师傅博客园博客,原文链接:http://www.cnblogs.com/youring2/archive/2012/02/20/2359214.html,如需转载请自行联系原作者