TSQL递归更新?

时间:2010-12-01 13:17:39

标签: tsql recursion common-table-expression

我想知道在tsql(CTE)中是否存在递归更新

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

我可以使用例如从ID = 6的CTE到最顶行来递归更新列value吗?

1 个答案:

答案 0 :(得分: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;
相关问题