【问题标题】:TSQL A recursive update?TSQL 递归更新?
【发布时间】:2010-12-01 13:17:38
【问题描述】:

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

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

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

【问题讨论】:

  • 你想用什么来更新它?程序循环可以吗?还是要求全部在一个更新语句中?
  • 我写错了,再看最后一句

标签: tsql recursion common-table-expression


【解决方案1】:

是的,应该是。 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;

【讨论】:

  • CTE 本身不可更新。这给出了错误Derived table 'DirectReports' is not updatable because a column of the derived table is derived or constant.
  • 天啊,当然……我们可以在更新查询中加入 CTE 表,这解决了我所有的问题……我欠你一杯啤酒,伙计;)谢谢!
  • @Tony - 不要打扰。只要您接受我的回答,以后称我为“陛下”,就完全足够了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2020-09-05
  • 2012-03-17
  • 2010-09-21
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多