SQL循环更新和更新后触发与聚合函数

时间:2013-11-26 18:56:00

标签: sql sql-server database stored-procedures

我有Update语句和AFTER更新触发器。当我没有使用聚合函数或在触发器上选择然后触发器在我放置聚合函数或选择然后取最后插入的值并更新与给定条件匹配的所有行时,更新语句正在循环中发生/ p>

ALTER TRIGGER UpdateGrossPay
ON DailyClocking
AFTER UPDATE
AS
UPDATE Daily
SET GrossPay=(SELECT PayRate FROM inserted WHERE
Daily.ClockDate=inserted.ClockDate)

GO

我需要select语句,因为我必须在其上使用聚合函数 该功能是

SET GrossPay=((SELECT (sum(datediff(minute, 0,inserted.TotalHours))) / 60.0
FROM inserted WHERE Daily.ClockDate=inserted.ClockDate)*(SELECT PayRate from inserted))

帮我这样做。对不起,我是触发器的新手

修改

ALTER TRIGGER UpdateGrossPay ON DailyClocking AFTER UPDATE AS DECLARE @rs int; SET @rs=10

UPDATE DailyClocking SET GrossPay=@rs*PayRate GO

这不需要更新条件。什么行更新然后触发器将更新与该行PayRate相同的行此TRIGGER工作正常

编辑2

ALTER TRIGGER GrossPay ON Daily AFTER UPDATE AS

UPDATE Daily SET GrossPay=(datediff(minute, 0, Daily.TotalHours) / 60.0)*Daily.PayRate FROM Daily,inserted WHERE Daily.ClockDate=inserted.ClockDate AND Daily.HId=inserted.HlId AND Daily.RId=inserted.RId

1 个答案:

答案 0 :(得分:2)

如果您更新多个记录,您的触发器将在“inserted”表中触发多行,因此您必须使用插入的DailyClocking加入Dayly表。 在触发器中总是假设您将插入和删除多条记录。 例如(也许您应该在员工ID上添加联接或准确的事情)

UPDATE Daily
SET GrossPay= (datediff(minute, 0,inserted.TotalHours) / 60.0 ) * PayRate 
FROM Daily
INNER JOIN INSERTED on Daily.ClockDate=inserted.ClockDate
and Daily.someId = inserted.SomeId  -- perhaps add some id here ? (employee or other)