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

后端 未结 9 529
眼角桃花
眼角桃花 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

    All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.

    To do something before an update, check out INSTEAD OF UPDATE Triggers.

    0 讨论(0)
  • 2020-11-28 11:05

    T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.

    I believe you will want to use an INSTEAD OF trigger.

    0 讨论(0)
  • 2020-11-28 11:10

    Full example:

    CREATE TRIGGER [dbo].[trig_020_Original_010_010_Gamechanger]
       ON  [dbo].[T_Original]
       AFTER UPDATE
    AS 
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
        DECLARE @Old_Gamechanger int;
        DECLARE @New_Gamechanger int;
    
        -- Insert statements for trigger here
        SELECT @Old_Gamechanger = Gamechanger from DELETED;
        SELECT @New_Gamechanger = Gamechanger from INSERTED;
    
        IF @Old_Gamechanger != @New_Gamechanger
    
            BEGIN
    
                INSERT INTO [dbo].T_History(ChangeDate, Reason, Callcenter_ID, Old_Gamechanger, New_Gamechanger)
                SELECT GETDATE(), 'Time for a change', Callcenter_ID, @Old_Gamechanger, @New_Gamechanger
                    FROM deleted
                ;
    
            END
    
    END
    
    0 讨论(0)
提交回复
热议问题