【问题标题】:Writing trigger on a column在列上写入触发器
【发布时间】:2016-02-27 18:51:19
【问题描述】:

是否可以编写一个仅在特定列被更新时才执行的更新触发器?

例如:我有一个表 Table1 与列 column1column2column3

我想创建一个更新触发器,该触发器仅在 column3 更新时执行。

【问题讨论】:

标签: sql sql-server triggers


【解决方案1】:

您不能编写仅在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2014-10-09
    • 2020-01-06
    • 1970-01-01
    • 2022-07-12
    • 2020-04-12
    相关资源
    最近更新 更多