简体   繁体   English

SQL 插入触发器,用于插入更新

[英]SQL insert trigger for insert with update

I have two tables:我有两张桌子:

[1] Donations - with amount and pet_id field [1] 捐款 - 带有金额和 pet_id 字段

[2] Pets - with id and total donations field [2] 宠物 - 带有 id 和总捐款字段

I'm trying to create a trigger which will update total donations field whenever a new row is being inserted to Donations table.我正在尝试创建一个触发器,该触发器将在将新行插入 Donations 表时更新总捐赠字段。 I tried this one:我试过这个:

create trigger update_donations
on sponserships
for insert
as
   update dbo.Pets 
   set tot_donations = (
      select new_val = inserted.amount + pets.tot_donations
      from inserted
      where inserted.[Pet-ID] = pets.[Animal-ID]
   )

But of course it changes all records, whereas i want to change only records that are changed in the donations table.但当然它会更改所有记录,而我只想更改捐赠表中更改的记录。

It is usually not a good practice to store this type of derived information - you could have a view that computes it on the fly rather than a trigger that keeps it up to date.存储这种类型的派生信息通常不是一个好习惯——你可以有一个动态计算它的视图,而不是一个让它保持最新的触发器。 Also please note that if you go that way, you also need a delete and an update trigger...另请注意,如果您采用 go 方式,您还需要deleteupdate触发器...

That said, you can use the following query in your insert trigger to update the relevant record in the pets table:也就是说,您可以在insert触发器中使用以下查询来更新 pets 表中的相关记录:

update p
set p.total_donations = p.total_donations + i.amount    
from dbo.Pets p
inner join inserted i on i.[Pet-ID] = p.[Animal-ID]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM