【问题标题】:Triggers execution after group update with "in (...)" statement in query在查询中使用“in (...)”语句进行组更新后触发执行
【发布时间】:2015-12-21 21:47:39
【问题描述】:

我在表中有 AFTER UPDATE 触发器:

ALTER TRIGGER [dbo].[table1] 
   ON  [dbo].[table]
   AFTER UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @primaryKey bigint
    SELECT @PrimaryKey = PK FROM Inserted
    if EXISTS(select * from [dbo].[table1] where PK=@PrimaryKey)
    begin
        update [dbo].[table1] set [Action] = 'U' where PK=@PrimaryKey
    end
    else
    begin
        insert into [dbo].[table1] ([PK], [Action], StampIn) 
        values (@PrimaryKey, 'U', GETDATE())
    end
END

当我执行“更新 SOME_DB.dbo.TABLE set FIELD='NEW VALUE' where PK in (3,4,5)”时,我发现只有一行添加到 PK 为“3”的 table1。这意味着触发器在表中只执行了一次。

但我需要让 table1 中的所有行都更新了 PK。

你能帮我解决我的问题吗?

谢谢。

【问题讨论】:

  • SQL Server 触发器在整个语句中执行一次,而不是逐行执行。

标签: sql sql-server tsql triggers


【解决方案1】:

SQL 触发器使用inserted 视图来识别所有正在插入的行。您的逻辑只查看其中一行;因此它不符合您的期望。所以:

BEGIN
    SET NOCOUNT ON;

    update t1
         set [Action] = 'U'
         from table1 t1 join
              inserted i
              on i.primarykey = t1.pk ;
    insert into [dbo].[table1] ([PK], [Action], StampIn) 
       select i.primarykey, 'U', getdate()
       from inserted i
       where not exists (select 1 from dbo.table1 t1 where t1.pk = i.primarykey);
END;

您实际上并不需要条件逻辑,因为 joinwhere 子句负责处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2013-01-16
    • 2012-07-04
    • 2021-11-03
    相关资源
    最近更新 更多