0
votes

I need to create an audit record for table changes. I was reading the following answer: SQL Insert/Update/Delete Trigger Efficiency

My audit table has the following columns:

audit_id
audit_date
audit_user
audit_table_name -> table name being audited
audit_table_id -> id of the row being audited
audit_parent_name -> parent table name if this table is a child
audit_parent_id -> parent id (is a foreign key in this table)
audit_type -> insert, update, delete
audit_fields -> all fields that were affected

The tricky part is that audit_fields has the following format:

column_name + chr(1) + old_value + chr(1) + new_value + chr(10) ...

Can this be achieved with a trigger and how exactly?

EDIT:

I'm basing my trigger on the following answer: SQL Server auto audit updated column

The trigger works fine if I use that same table. However, how can I concatenate the changed fields in the format I need and insert just 1 record in the audit table?

1

1 Answers

0
votes

Here is simple example of using INSTEAD OF UPDATE trigger to capture before and after value of column and storing it into another table.

IF OBJECT_ID('dbo.test1') IS NOT NULL DROP TABLE test1
IF OBJECT_ID('dbo.test2') IS NOT NULL DROP TABLE test2

CREATE TABLE Test1 ( Id INT, value VARCHAR(20) )
GO
CREATE  TABLE Test2 (TableName VARCHAR(100), ValueChanged VARCHAR(250) )
GO
CREATE TRIGGER test1_Update ON dbo.Test1
    INSTEAD OF UPDATE
AS
    INSERT INTO dbo.Test2
            ( TableName
            ,ValueChanged
            )
            SELECT 'Test1'
                    ,'value' + ' ' + t.value + ' ' + i.value + ';'
                FROM INSERTED AS i
                JOIN Test1 AS t
                    ON i.id = t.id;
    UPDATE dbo.Test1
        SET value = INSERTED.value
        FROM INSERTED
        WHERE test1.Id = INSERTED.id
go

SELECT * FROM test1

INSERT INTO dbo.Test1 VALUES (1, 'Data'),(2,'Data')

SELECT * FROM test1

UPDATE test1 
SET value = 'MyNew Data 1 '
WHERE id = 1

SELECT * FROM test1
SELECT * FROM test2