Sql-Server

如何在 AFTER UPDATE 觸發器中僅引用受影響的行

  • January 12, 2017

我有這張桌子:

在此處輸入圖像描述

而且我正在嘗試創建一個更新觸發器,每當對或列執行更新時,它將更新last_updated_on = GETDATE()和列。last_updated_by = SYSTEM_USER``step_number``step_name

我開始創建它

ALTER TRIGGER tr_app_bread_crumbs_afterupdate
ON [dbo].[app_bread_crumbs]
AFTER UPDATE
AS
BEGIN 
   UPDATE [dbo].[app_bread_crumbs]
   SET last_updated_by = SYSTEM_USER,
   last_updated_on = GETDATE()
END

但這將立即更新所有行。我試圖弄清楚如何指定僅更新last_updated_on以及last_updated_by通過觸發器來指定進行更新的特定行。

例如,如果他們更新:

UPDATE [dbo].[app_bread_crumbs]
   SET step_name = 'DAMAGE' WHERE step_number = 1

觸發器應該只更新第一行

使用該inserted表,這是一個在觸發器內部可用的特殊表,其中包含將被更新/插入到表中的行。

ALTER TRIGGER tr_app_bread_crumbs_afterupdate
ON [dbo].[app_bread_crumbs]
AFTER UPDATE
AS
BEGIN 
   UPDATE [dbo].[app_bread_crumbs]
   SET last_updated_by = SYSTEM_USER,
   last_updated_on = GETDATE()
   FROM dbo.app_bread_crumbs abc
   WHERE EXISTS (SELECT 1 FROM inserted i WHERE i.id = abc.id);
END

您需要使用INSERTEDDELETED偽表。一種方法:

ALTER TRIGGER tr_app_bread_crumbs_afterupdate
ON [dbo].[app_bread_crumbs]
AFTER UPDATE
AS
BEGIN
   UPDATE upd
   SET last_updated_by = SYSTEM_USER,
       last_updated_on = GETDATE()
   FROM [dbo].[app_bread_crumbs] AS upd
     JOIN Inserted AS i
       ON i.id = upd.id
     JOIN Deleted AS d
       ON d.id = i.id
   WHERE NOT EXISTS                              -- only when any      
           ( SELECT i.sep_number, i.step_name    -- of the 2 columns
           INTERSECT                             -- changed
             SELECT d.sep_number, d.step_name
           ) ;
END ;

引用自:https://dba.stackexchange.com/questions/118648