注意:由於可能有更多的Table1記錄同時具有相同的密鑰更新,因此必須對這些差異進行求和,僅將彙總權重放在正面和負面的彙總字段中。試圖在沒有求和的情況下這樣做會失敗,因爲只有具有相同密鑰的最後一行將被記錄,其餘的將被丟棄。
alter trigger theTrigger on Table1
after update, insert
as
set NoCount ON
if update(Value)
begin
-- Add missing records to summary table
insert into table2 (Key, positive_sum, negative_sum)
select distinct Key, 0, 0
from Inserted
where not exists (select null from table2 t2 where t2.Key = Inserted.Key)
-- Update summary
update table2
set Positive_sum = isnull(positive_sum, 0) + isnull (diff.Positives, 0),
Negative_sum = isnull(Negative_sum, 0) + isnull (diff.Negatives, 0)
from table2
-- One can have only one record per key because otherwise sums would not be correct.
inner join (select Inserted.Key,
sum (case when Inserted.Value > isnull(Deleted.Value, 0) then Inserted.Value - isnull(Deleted.Value, 0) end) Positives,
sum (case when Inserted.Value < isnull(Deleted.Value, 0) then isnull(Deleted.Value, 0) - Inserted.Value end) Negatives,
from Inserted
left join Deleted on Inserted.ID = Deleted.ID
group by Inserted.Key
) diff
on table2.Key = diff.Key
end
所以,做的「鑰匙」已經存在於'Table2'?還是你必須先檢查表上的所有腦幹做一個'INSERT'然後一個'UPDATE'? – Lamak 2012-03-13 12:10:54
什麼部分你不明白,或者你只是希望有人爲你寫一個完整的觸發器? – JeffO 2012-03-13 12:37:49