Create a trigger that inserts values into a new table when a column is updated

后端 未结 4 1232
我在风中等你
我在风中等你 2021-02-03 11:21

I\'ve been looking at some previous answers on triggers on here but can\'t find what I need exactly but I\'m sure my question has been asked/answered before.

I\'m tryin

4条回答
  •  悲哀的现实
    2021-02-03 11:58

    Something like this should do what you need. You would have the INSERT statements below insert values indicating the operation performed into MyLogTable.

    CREATE TRIGGER [dbo].[TRIG_MyTable]
    ON [dbo].[MyTable]
    AFTER INSERT, UPDATE
    
    AS 
    
    DECLARE @INS int, @DEL int
    
    SELECT @INS = COUNT(*) FROM INSERTED
    SELECT @DEL = COUNT(*) FROM DELETED
    
    IF @INS > 0 AND @DEL > 0 
    BEGIN
    
        -- a record got updated, so log accordingly.
    
        INSERT INTO MyLogTable
        SELECT 'New Values', getdate() FROM INSERTED
    
        INSERT INTO MyLogTable
        SELECT 'Old Values', getdate() FROM DELETED
    
    END
    
    ELSE 
    BEGIN
    
        -- a new record was inserted.
    
        INSERT INTO MyLogTable
        SELECT 'Insert', getdate() FROM INSERTED
    
    END
    

    If you wanted to you could also add columns from INSERTED and DELETED to your log table as well if you wanted to capture the actual column values that got inserted or updated.

提交回复
热议问题