是否可以编写更新触发器,仅在特定列更新时执行?
例如:我有一个表Table1
,其中包含column1
,column2
,column3
列。
我想创建一个更新触发器,仅在column3
更新时执行。
答案 0 :(得分:0)
您无法编写仅在column3
更新时执行的触发器 - 表格上的触发器,并且每次表上的某些内容发生更改时都会触发
但是在触发器内部,您可以检查column3
是否已更新,如果已更新,您可以执行某些操作。
像
这样的东西CREATE TRIGGER updateTrigger
ON dbo.YourTableName
AFTER UPDATE
AS
-- the "deleted" pseudo table contains the old values before the update,
-- the "Inserted" table the new values after the update
-- but DO REMEMBER: the trigger is run **once per statement** - so
-- both tables will most likely contain *multiple rows* and you need
-- to work with that
-- Scenario here: insert data into an "Audit" table if "column3" changed
INSERT INTO dbo.Audit (ID, OldValueCol3, NewValueCol3)
SELECT
d.Id, d.Column3, i.Column3
FROM
Deleted d
INNER JOIN
Inserted i ON d.ID = i.ID -- join on the primary key
WHERE
d.Column3 <> i.Column3 -- use those rows where "column3" changed