Trigger Assistance

问题描述 投票:0回答:1

我试图创建一个触发器,使其仅在某个列被更新时才触发,然后仅在该列被更新为“已执行”时才触发。如果列已更改,我可以更新,但是如果列已更新为“已执行”,我似乎找不到更新的方法]

CREATE TRIGGER dbo.NewTrigger
   ON  dbo.Database
   AFTER UPDATE
AS 
IF Update(Status) = 'Executed'

    BEGIN 
--MY insert into statement.  This adds data to another table, but I only want the whole process to run if the original table column "Status" is set to "Executed"

END

有人可以帮忙吗?

sql sql-server database-trigger
1个回答
1
投票

您需要在触发器中使用inserteddeleted表,请参见此处:

Use Inserted and Deleted Tables

[如果是update

inserted表:包含已更新的行的新列值deleted表:包含已更新的行的旧列值

您的触发器可能看起来像这样:

create table t (id int identity, status varchar(100));
create table audit(id int, old_status varchar(100), new_status varchar(100), updated_at datetime);
create trigger StatusUpdate
on t
After UPDATE as

if (update(status) 
       and exists(select * from inserted i 
                  inner join deleted d on d.id = i.id
                  where d.status != 'Executed' 
                  and i.status = 'Executed'))
begin
insert into audit (id, old_status, new_status, updated_at)
  select i.id, d.status, i.status, getdate() 
  from inserted i 
  inner join deleted d on d.id = i.id
  where d.status != 'Executed' 
  and i.status = 'Executed'
end

请参阅Demo on DB Fiddle

[Demo 2-多行一起更新

© www.soinside.com 2019 - 2024. All rights reserved.