我试图创建一个触发器,使其仅在某个列被更新时才触发,然后仅在该列被更新为“已执行”时才触发。如果列已更改,我可以更新,但是如果列已更新为“已执行”,我似乎找不到更新的方法]
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
有人可以帮忙吗?
您需要在触发器中使用inserted
和deleted
表,请参见此处:
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 2-多行一起更新