我想在特定列上发生更新之前将一行从一个表复制到另一个表。这个列在我的表中名为StartDateTime_
。
任何人都可以纠正这个触发器,如果它不正确或需要优化。
CREATE TRIGGER PeriodicHistory_TR_U ON order_db..Periodic
FOR UPDATE
AS IF update(StartDateTime_)
begin
declare @Identity_;
declare @Version_;
DECLARE @Revision_;
declare @Identifier_;
declare @CreationTime_;
declare @CreationUserId_;
declare @StartDateTime_;
SELECT @Identity_= i.Identity_ from inserted i;
SELECT @Version_= i.Version_ from inserted i;
SELECT @Identifier_= i.Identifier_ from inserted i;
SELECT @CreationTime_= i.CreationTime_ from inserted i;
SELECT @CreationUserId_= i.CreationUserId_ from inserted i;
SELECT @StartDateTime_= i.StartDateTime_ from inserted i;
set @Revision_ = @Version_ +1;
insert into order_db..PeriodicHistory(Identity_,Version_,Revision_,Identifier_,CreationTime_,CreationUserId_,StartDateTime_)
values(@Identity_,@Version_,@Identifier_,@CreationTime_,@CreationUserId_,@StartDateTime_);
end
答案 0 :(得分:1)
这个怎么样:
CREATE TRIGGER PeriodicHistory_TR_U ON Periodic
FOR UPDATE
AS IF update(StartDateTime_)
BEGIN
INSERT INTO PeriodicHistory(Identity_,Version_,Revision_,Identifier_,CreationTime_,CreationUserId_,StartDateTime_)
SELECT d.Identity_,d.Version_,d.Revision_ + 1,d.Identifier_,d.CreationTime_,d.CreationUserId_,d.StartDateTime_
FROM deleted d
JOIN inserted i
ON d.Identity_ = i.Identity_
END
这消除了对临时变量的需求。
考虑如果Periodic上的更新影响多行,会发生什么。原始触发器无法存储多个值......
此外,我修改后的触发器以与原始触发器相同的方式更新历史记录表中的版本。您可能希望更新Periodic表中的版本并将旧值保留在历史记录中。因为它是十次更新后你可能最终得到:Periodic.Version_ = 1 PeriodicHistory.Version_ = 2