3

I'm wondering if exists a recursive update in tsql (CTE)

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

I it possible to update the column value recursively using e.g CTE from ID = 6 to the top most row ?

KM.
  • 101,727
  • 34
  • 178
  • 212
Tony
  • 12,405
  • 36
  • 126
  • 226

1 Answers1

8

Yes, it should be. 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;
Vilx-
  • 104,512
  • 87
  • 279
  • 422
  • The CTE itself isn't updatable though. This gives the error `Derived table 'DirectReports' is not updatable because a column of the derived table is derived or constant.` – Martin Smith Dec 01 '10 at 13:27
  • geez, of course... we can join the CTE table in the update query, that solves all my problems... I owe You a beer, man ;) thanks ! – Tony Dec 01 '10 at 13:30
  • 3
    @Tony - don't bother. It'll be completely sufficient if you just accept my answer and henceforth refer to me as "Your Majesty". :) – Vilx- Dec 01 '10 at 13:31