我有一张桌子(见图)员工(经理是另一个经理,依此类推),id、parentid、salary、totalsalary。最后一个需要更新,以便每个员工都有其后代工资的总和。我已经编写了脚本,它通过 id 获取总工资,而不是更新光标中的列,但它很重......还有其他方式吗?
DECLARE @id INT ;
DECLARE @s INT ;
DECLARE curs CURSOR FOR
SELECT personid FROM dbo.Employees
OPEN curs ;
FETCH NEXT FROM curs INTO @id ;
WHILE @@FETCH_STATUS = 0
BEGIN
WITH Xemps ( ID )
AS ( SELECT PersonID AS ID
FROM dbo.Employees
WHERE PersonID = @id
UNION ALL
SELECT e.PersonID AS ID
FROM dbo.Employees AS e
INNER JOIN Xemps AS x ON e.ManagerID = x.ID
)
SELECT @s = SUM(Salary)
FROM dbo.Employees
WHERE PersonID IN ( SELECT id
FROM Xemps )
UPDATE dbo.Employees
SET SalarySum = @s
WHERE PersonID = @id
FETCH NEXT FROM curs INTO @id
END
CLOSE curs ;
DEALLOCATE curs ;