2015-12-21 35 views
1

我有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 [email protected]) 
    begin 
     update [dbo].[table1] set [Action] = 'U' where [email protected] 
    end 
    else 
    begin 
     insert into [dbo].[table1] ([PK], [Action], StampIn) 
     values (@PrimaryKey, 'U', GETDATE()) 
    end 
END 

当我做“更新SOME_DB.dbo.TABLE设置字段=” NEW VALUE'其中PK在(3,4,5)“中,我发现只有一行被添加到table1,PK”3“。这意味着触发器在表中只执行一次。

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

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

谢谢。

+1

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

回答

3

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条款采取照顾。

+0

谢谢。这是工作。 –

相关问题