[英]How to use trigger to update column for newly inserted tuple
I have a table BillRecords我有一张表 BillRecords
bill_id buy_amt sell_amt profit
----------------------------------------------------
0 200 300 NULL
1 1000 1200 NULL
Let's say I want to insert following record假设我想插入以下记录
INSERT INTO BillRecords(bill_id, buy_amt, sell_amt)
VALUES (2, 2000, 2500)
I'm expecting that as soon as I insert record, trigger should only update profit column for newly inserted record (ie WHERE bill_id = 2) and not for all the rows in profit column.我期望一旦我插入记录,触发器应该只为新插入的记录(即 WHERE bill_id = 2)更新利润列,而不是为利润列中的所有行更新。 What should I do?
我该怎么办?
Note: I'm using SQL Server注意:我使用的是 SQL Server
No need for a trigger to do what you want.不需要触发器来做你想做的事。 It is much simpler, and more efficient, to use a computed column:
使用计算列更简单、更高效:
create table billrecords (
bill_id int primary key,
buy_amt int,
sell_amt int,
profit as (buy_amt - sell_amt)
);
Or if you want to add it to an already-existing table:或者,如果要将其添加到已存在的表中:
alter table billrecords
add profit as (buy_amt - sell_amt);
This gives you an always up-to-date value, that you can access just like any other column.这为您提供了始终最新的值,您可以像访问任何其他列一样访问该值。 For better performance, you can use option
persisted
, so the value column is physically stored, and recomputed only when needed instead of every time it is accessed.为了获得更好的性能,您可以使用选项
persisted
,因此值列是物理存储的,并且仅在需要时重新计算,而不是每次访问时重新计算。
Since you only want to update the profit amount of the transaction having bill_id = 2, you can use the below after trigger this in combination with a derived column "profit" which fetches the profit amount.由于您只想更新 bill_id = 2 的交易的利润金额,因此您可以在触发后使用以下内容与获取利润金额的派生列“利润”结合使用。
CREATE TRIGGER trigger_name
ON billrecords
After INSERT
AS
IF EXISTS (SELECT * from inserted)
begin
update m
set m.profit = m.sell_amt - m.bill_amt, m.bill_amt = null, m.sell_amt = null
from billrecords m join inserted i
on i.bill_id = m.bill_id
where i.bill_id = 2
end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.