2015-12-21 82 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

謝謝。這是工作。 –

相關問題