1
SQL Server中需要的解决方案。如何编写满足以下场景的查询/触发器?
假设有2个表
TICKET
表列如下:- ITEM_ID - PK
- ticket_cost
TICKET_PAST
与列:- 价格 - FK
- ticket_new_cost
问题是写一个触发器这样,每当在TICKET
表中的价格被插入,更新或删除应由产生一个新行触发?
SQL Server中需要的解决方案。如何编写满足以下场景的查询/触发器?
假设有2个表
TICKET
表列如下:
TICKET_PAST
与列:
问题是写一个触发器这样,每当在TICKET
表中的价格被插入,更新或删除应由产生一个新行触发?
使用的after update
触发,并访问来自inserted
新的价值和deleted
旧值:
create trigger dbo.item_price_update_trigger
on dbo.item
after update as
begin;
set nocount on;
insert into item_hist (item_id, price, new_price)
select i.item_id, d.price, i.price
from inserted i
inner join deleted d
on i.item_id = d.item_id
end;
go
rextester演示:http://rextester.com/PBB85814
after insert
存储项目的初始插件,以及
after delete
触发记录已删除项目的最终价格。
您也可能想要包括发生这些操作的日期,以便您可以查询给定时间项目的有效价格。
创建审计/历史记录表及相关触发器的有些自动化的选项,这篇文章和相关的脚本可能会有所帮助:Quick And Easy Audit Tables - Dave Britten
参考:
您将需要'item_id'作为'item_hist'表中的外键。 – SqlZim