How can I do a BEFORE UPDATED trigger with sql server?

后端 未结 9 564
眼角桃花
眼角桃花 2020-11-28 10:18

I\'m using Sqlserver express and I can\'t do before updated trigger. There\'s a other way to do that?

9条回答
  •  一向
    一向 (楼主)
    2020-11-28 10:56

    Can't be sure if this applied to SQL Server Express, but you can still access the "before" data even if your trigger is happening AFTER the update. You need to read the data from either the deleted or inserted table that is created on the fly when the table is changed. This is essentially what @Stamen says, but I still needed to explore further to understand that (helpful!) answer.

    The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table...

    The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table...

    https://msdn.microsoft.com/en-us/library/ms191300.aspx

    So you can create your trigger to read data from one of those tables, e.g.

    CREATE TRIGGER  ON 
    AFTER UPDATE
    AS
      BEGIN
        INSERT INTO  ( , DateChanged )
        SELECT , getdate()
        FROM deleted;
      END;
    

    My example is based on the one here:

    http://www.seemoredata.com/en/showthread.php?134-Example-of-BEFORE-UPDATE-trigger-in-Sql-Server-good-for-Type-2-dimension-table-updates

    sql-server triggers

提交回复
热议问题