SQL Server创建审计触发器

时间:2014-03-26 13:55:32

标签: sql sql-server-2008 triggers

我需要为表更改创建审核记录。我正在阅读以下答案: SQL Insert/Update/Delete Trigger Efficiency

我的审核表包含以下列:

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

棘手的部分是audit_fields具有以下格式:

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

这可以通过触发器实现吗?

编辑:

我的触发器基于以下答案: SQL Server auto audit updated column

如果我使用同一个表,触发器工作正常。但是,如何以我需要的格式连接已更改的字段,并在审计表中只插入1条记录?

1 个答案:

答案 0 :(得分:0)

以下是使用INSTEAD OF UPDATE触发器捕获列的值之前和之后并将其存储到另一个表中的简单示例。

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