使触发器仅在特定列更新时触发

Make a trigger to only trigger if a certain column is updated

我正在尝试使触发器仅在特定列更新时触发,然后仅在该列更新为 'Executed' 时触发。如果列已更改,我可以更新,但如果列更新为 'Executed'

,我似乎找不到更新方法
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

有人可以帮忙吗?

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

Use Inserted and Deleted Tables

update 的情况下:

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

您的触发器可能如下所示:

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 - 多行一起更新