注意:由于可能有更多的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