2010-12-01 150 views
3

我不知道是否存在於TSQL(CTE)遞歸更新TSQL遞歸更新?

ID parentID value 
-- -------- ----- 
1 NULL  0 
2 1  0 
3 2  0 
4 3  0 
5 4  0 
6 5  0 

我能夠更新列value遞歸使用e.g CTE從ID = 6至最頂部行?

+0

您想更新什麼?是一個程序循環好嗎?或者是單個更新聲明中的全部要求? – Randy 2010-12-01 13:19:53

+0

我犯了一個錯誤,再讀一遍最後一句 – Tony 2010-12-01 13:22:25

回答

8

是的,應該是。 MSDN gives an example

USE AdventureWorks; 
GO 
WITH DirectReports(EmployeeID, NewVacationHours, EmployeeLevel) 
AS 
(SELECT e.EmployeeID, e.VacationHours, 1 
    FROM HumanResources.Employee AS e 
    WHERE e.ManagerID = 12 
    UNION ALL 
    SELECT e.EmployeeID, e.VacationHours, EmployeeLevel + 1 
    FROM HumanResources.Employee as e 
    JOIN DirectReports AS d ON e.ManagerID = d.EmployeeID 
) 
UPDATE HumanResources.Employee 
SET VacationHours = VacationHours * 1.25 
FROM HumanResources.Employee AS e 
JOIN DirectReports AS d ON e.EmployeeID = d.EmployeeID;