Table history trigger in SQL Server?

前端 未结 3 1642
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 18:06

I\'d like to create a trigger that writes to a history table with inserted values and before and after update values. I would also like to include as much information about

3条回答
  •  無奈伤痛
    2020-12-10 18:40

    If each user has an account, you can use the SYSTEM_USER function to determine the current user. However, if all your connections go through a proxy account, as is typical in most web site setups, then you have to rely on the proper userId being passed to the Update statement:

    CREATE TRIGGER [update_history] ON MyTable
    FOR UPDATE
    AS
    INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
    SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'BEFORE UPDATE', inserted.userId
    FROM MyTable
        Join inserted
            On inserted.id = MyTable.id
    
    INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
    SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'AFTER UPDATE', userId
    FROM inserted
    

提交回复
热议问题