首先 你在這裡 OPTION (MAXRECURSION 2) 無非就是想控制遞迴次數
你可以這樣做
--Creates an infinite loop
WITH cte (EmployeeID, ManagerID, Title,lev) as
(
SELECT EmployeeID, ManagerID, Title,lev=1
FROM HumanResources.Employee
WHERE ManagerID IS NOT NULL
UNION ALL
SELECT cte.EmployeeID, cte.ManagerID, cte.Title,cte.lev+1
FROM cte
JOIN HumanResources.Employee AS e
ON cte.ManagerID = e.EmployeeID
where cte.lev
)
--Uses MAXRECURSION to limit the recursive levels to 2
SELECT EmployeeID, ManagerID, Title
FROM cte;
GO
注意我這裡多了 lev 透過lev的數值大小來控制迴圈遞迴次數
2.OPTION (MAXRECURSION 0);
可以執行,但是出現死迴圈,在表最後一條記錄數出現死迴圈。
===》
那是因為你的遞迴沒有出口
首先 你在這裡 OPTION (MAXRECURSION 2) 無非就是想控制遞迴次數
你可以這樣做
--Creates an infinite loop
WITH cte (EmployeeID, ManagerID, Title,lev) as
(
SELECT EmployeeID, ManagerID, Title,lev=1
FROM HumanResources.Employee
WHERE ManagerID IS NOT NULL
UNION ALL
SELECT cte.EmployeeID, cte.ManagerID, cte.Title,cte.lev+1
FROM cte
JOIN HumanResources.Employee AS e
ON cte.ManagerID = e.EmployeeID
where cte.lev
)
--Uses MAXRECURSION to limit the recursive levels to 2
SELECT EmployeeID, ManagerID, Title
FROM cte;
GO
注意我這裡多了 lev 透過lev的數值大小來控制迴圈遞迴次數
2.OPTION (MAXRECURSION 0);
可以執行,但是出現死迴圈,在表最後一條記錄數出現死迴圈。
===》
那是因為你的遞迴沒有出口