Sql-Server
如何在 AFTER UPDATE 觸發器中僅引用受影響的行
我有這張桌子:
而且我正在嘗試創建一個更新觸發器,每當對或列執行更新時,它將更新
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
您需要使用
INSERTED
和DELETED
偽表。一種方法: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 ;