Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使触发器仅在某列更新时触发_Sql_Sql Server_Database Trigger - Fatal编程技术网

Sql 使触发器仅在某列更新时触发

Sql 使触发器仅在某列更新时触发,sql,sql-server,database-trigger,Sql,Sql Server,Database Trigger,我试图使触发器仅在某个列更新时触发,然后仅在该列更新为“已执行”时触发。如果列被更改,我可以更新,但如果列被更新为“已执行”,我似乎找不到更新的方法 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,

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

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
有人可以帮忙吗?

您需要使用触发器中插入和删除的表,请参见此处:

在更新的情况下:

插入的表:包含已更新行的新列值 已删除表:包含已更新行的旧列值

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

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);


-多行同时更新

您好,感谢rohitvats,如果我正在进行的插入没有实际引用此表中的数据,这是否仍然有效。我的使用案例是我们想要做随机药物测试。我试图触发的这个表是测试日期表。当测试日期到期时,我希望它更新为executed(已执行),这将导致它检查我们的访问控制数据库,查看谁在现场,并选择一个随机选择,然后将该数据插入另一个表中。我已经让随机选择和插入语句很好地工作,但我只需要在Executed@ValiantSirDK是的,您可以在触发器中执行任何您想要的操作,您实际上不需要使用插入的和删除的表,只需要检查在这种情况下是否满足您的条件。当然,除非您需要更新表中的一些数据来进行后续插入,如上面的演示“插入到审计中”。谢谢Rohitvats。根据你给出的例子,我可以设置触发器!多谢各位
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