SQL Server表审核触发器

时间:2016-05-21 15:51:36

标签: sql sql-server xml tsql

我有两张表CustomersAuditTable。当我修改Customers表时,我需要在AuditTable中插入一条新记录:

CREATE TABLE [dbo].[AuditTable]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [StateBefore] [nvarchar](max) NULL,
    [StateAfter] [nvarchar](max) NULL
) 

我需要在更新之前和之后将Customer状态的XML表示放入StateBeforeStateAfter

Customer表是:

CREATE TABLE [dbo].[Customer]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    [Email] [nvarchar](max) NOT NULL,
    [IsDeleted] [bit] NULL,
    [CreatedUtc] [datetime] NOT NULL,
    [UpdatedUtc] [datetime] NULL,
    [Version] [timestamp] NOT NULL,

    CONSTRAINT [PK_dbo.Customer] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
           WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
                 ALLOW_PAGE_LOCKS = ON)
)
GO

ALTER TABLE [dbo].[Customer] 
   ADD DEFAULT (getutcdate()) FOR [CreatedUtc]
GO

我找到了如何获取行的xml表示的方法:

SELECT
    [State] = (SELECT *
               FROM dbo.Customer [Customer]
               WHERE [Customer].Id = cust.Id
               FOR XML AUTO
              )
FROM 
    dbo.Customer cust

仅举例来说。所以在我的触发器中,我需要创建来自deletedinserted表的行的xml表示。

这是触发器:

ALTER TRIGGER [dbo].[UpdateCustomerTrigger]
ON [dbo].[Customer]
FOR UPDATE
AS 
BEGIN
    UPDATE Customer 
    SET UpdatedUtc = GETDATE()
    FROM INSERTED
    WHERE inserted.id = Customer.Id

    -- here I need to insert new records into AuditTable
END

那么,我如何加入deletedinserted表的两个表示来正确地将它们插入AuditTable?感谢。

2 个答案:

答案 0 :(得分:4)

很高兴你已经找到了解决方案......

我只是在想类似的事情......

在任何微小变化时,您的方法都会完整记录的两个副本。因为我必须处理有很多列的表,其中一些是BLOB,这不适合我。

好吧,我没有找到一个绝对“干净”的方法,但是通过以下内容,您将获得一个AuditLog,其中仅包含已更改为更好阅读风格的值。

也许你喜欢它:

Test.scenario

编辑:添加了对INSERTDELETENULL值的支持。

尝试一下:

CREATE TABLE AuditTest(TableSchema VARCHAR(250), TableName VARCHAR(250), AuditType VARCHAR(250),Content XML, LogDate DATETIME DEFAULT GETDATE());
GO

CREATE TABLE dbo.Test(ID INT,Test1 VARCHAR(100),Test2 DATETIME,ModifyCounter INT DEFAULT 0,LastModified DATETIME DEFAULT GETDATE());
INSERT INTO dbo.Test(ID,Test1,Test2) VALUES
 (1,'Test1',{d'2001-01-01'})
,(2,'Test2',{d'2002-02-02'});

- 当前内容

SELECT * FROM dbo.Test;
GO

- 审核的触发器

CREATE TRIGGER [dbo].[UpdateTestTrigger]
ON [dbo].[Test]
FOR UPDATE,INSERT,DELETE
AS 
BEGIN
   IF NOT EXISTS(SELECT 1 FROM deleted) AND NOT EXISTS(SELECT 1 FROM inserted) RETURN;

   DECLARE @tp VARCHAR(10)=CASE WHEN EXISTS(SELECT 1 FROM deleted) AND EXISTS(SELECT 1 FROM inserted) THEN 'upd'
                           ELSE CASE WHEN EXISTS(SELECT 1 FROM deleted) AND NOT EXISTS(SELECT 1 FROM inserted) THEN 'del' ELSE 'ins' END END;
   WITH UpdateableCTE AS
   (
    SELECT t.LastModified,t.ModifyCounter 
    FROM dbo.Test AS t
    INNER JOIN inserted AS i ON t.ID=i.ID
   )
   UPDATE UpdateableCTE SET LastModified=GETDATE()
                           ,ModifyCounter=ModifyCounter+1;

   SELECT * INTO #tmpInserted FROM inserted;
   SELECT * INTO #tmpDeleted FROM deleted;

   DECLARE @tableSchema VARCHAR(250)='dbo';
   DECLARE @tableName   VARCHAR(250)='Test';

   DECLARE @cols VARCHAR(MAX)=
   STUFF
   (
   (
    SELECT ',' + CASE WHEN @tp='upd' THEN 
           'CASE WHEN (i.[' + COLUMN_NAME + ']!=d.[' + COLUMN_NAME + '] ' +
           'OR (i.[' + COLUMN_NAME + '] IS NULL AND d.[' + COLUMN_NAME + '] IS NOT NULL) ' + 
           'OR (i.['+ COLUMN_NAME + '] IS NOT NULL AND d.[' + COLUMN_NAME + '] IS NULL)) ' +
           'THEN ' ELSE '' END +
           '(SELECT ''' + COLUMN_NAME + ''' AS [@name]' + 
                         CASE WHEN @tp IN ('upd','del') THEN ',ISNULL(CAST(d.[' + COLUMN_NAME + '] AS NVARCHAR(MAX)),N''##NULL##'') AS [@old]' ELSE '' END + 
                         CASE WHEN @tp IN ('ins','upd') THEN ',ISNULL(CAST(i.[' + COLUMN_NAME + '] AS NVARCHAR(MAX)),N''##NULL##'') AS [@new] ' ELSE '' END + 
                  ' FOR XML PATH(''Column''),TYPE) ' + CASE WHEN @tp='upd' THEN 'END' ELSE '' END
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA=@tableSchema AND TABLE_NAME=@tableName
    FOR XML PATH('')
   ),1,1,''
   );

    DECLARE @cmd VARCHAR(MAX)=   
    'SET LANGUAGE ENGLISH;
    WITH ChangedColumns AS
    (
    SELECT COALESCE(i.ID,d.ID) AS ID
            ,Col.*  
    FROM #tmpInserted AS i
    FULL OUTER JOIN #tmpDeleted AS d ON i.ID=d.ID
    CROSS APPLY
    (
        SELECT ' + @cols + ' 
        FOR XML PATH(''''),TYPE
    ) AS Col([Column])
    )
    INSERT INTO AuditTest(TableSchema,TableName,AuditType,Content)
    SELECT ''' + @tableSchema + ''',''' + @tableName + ''',''' + @tp + '''
    ,(
    SELECT ''' + @tableSchema + ''' AS [@TableSchema]
            ,''' + @tableName + ''' AS [@TableName]
            ,''' + @tp + ''' AS [@ActionType]
    ,(
        SELECT ChangedColumns.ID AS [@ID]
        ,(
        SELECT x.[Column] AS [*],''''
        FROM ChangedColumns AS x WHERE x.ID=ChangedColumns.ID
        FOR XML PATH(''''),TYPE
        )
        FROM ChangedColumns
        FOR XML PATH(''Row''),TYPE
        )
    FOR XML PATH(''Changes'')
    );';

    EXEC (@cmd);

   DROP TABLE #tmpInserted;
   DROP TABLE #tmpDeleted;
END
GO

- 现在让我们用一些操作来测试它:

UPDATE dbo.Test SET Test1='New 1' WHERE ID=1;
UPDATE dbo.Test SET Test1='New 1',Test2={d'2000-01-01'} ;
DELETE FROM dbo.Test WHERE ID=2;
DELETE FROM dbo.Test WHERE ID=99; --no affect
INSERT INTO dbo.Test(ID,Test1,Test2) VALUES
 (3,'Test3',{d'2001-03-03'})
,(4,'Test4',{d'2001-04-04'})
,(5,'Test5',{d'2001-05-05'});
UPDATE dbo.Test SET Test2=NULL; --all rows
DELETE FROM dbo.Test WHERE ID IN (1,3);
GO

- 检查最终状态

SELECT * FROM dbo.Test;
SELECT * FROM AuditTest;
GO

- 清理

DROP TABLE dbo.Test;
GO
DROP TABLE dbo.AuditTest;
GO

第二个动作的结果:更新两行

<Changes TableSchema="dbo" TableName="Test" ActionType="upd">
  <Row ID="2">
    <Column name="Test1" old="Test2" new="New 1" />
    <Column name="Test2" old="Feb  2 2002 12:00AM" new="Jan  1 2000 12:00AM" />
  </Row>
  <Row ID="1">
    <Column name="Test2" old="Jan  1 2001 12:00AM" new="Jan  1 2000 12:00AM" />
  </Row>
</Changes>

INSERT操作的结果:三个新行

<Changes TableSchema="dbo" TableName="Test" ActionType="ins">
  <Row ID="5">
    <Column name="ID" new="5" />
    <Column name="Test1" new="Test5" />
    <Column name="Test2" new="May  5 2001 12:00AM" />
    <Column name="ModifyCounter" new="0" />
    <Column name="LastModified" new="Aug 18 2017  5:48PM" />
  </Row>
  <Row ID="4">
    <Column name="ID" new="4" />
    <Column name="Test1" new="Test4" />
    <Column name="Test2" new="Apr  4 2001 12:00AM" />
    <Column name="ModifyCounter" new="0" />
    <Column name="LastModified" new="Aug 18 2017  5:48PM" />
  </Row>
  <Row ID="3">
    <Column name="ID" new="3" />
    <Column name="Test1" new="Test3" />
    <Column name="Test2" new="Mar  3 2001 12:00AM" />
    <Column name="ModifyCounter" new="0" />
    <Column name="LastModified" new="Aug 18 2017  5:48PM" />
  </Row>
</Changes>

上次DELETE操作的结果

<Changes TableSchema="dbo" TableName="Test" ActionType="del">
  <Row ID="3">
    <Column name="ID" old="3" />
    <Column name="Test1" old="Test3" />
    <Column name="Test2" old="##NULL##" />
    <Column name="ModifyCounter" old="2" />
    <Column name="LastModified" old="Aug 18 2017  5:48PM" />
  </Row>
  <Row ID="1">
    <Column name="ID" old="1" />
    <Column name="Test1" old="New 1" />
    <Column name="Test2" old="##NULL##" />
    <Column name="ModifyCounter" old="3" />
    <Column name="LastModified" old="Aug 18 2017  5:48PM" />
  </Row>
</Changes>

答案 1 :(得分:2)

我找到了解决方案。这是触发器代码:

USE [ISContext]
GO
/****** Object:  Trigger [dbo].[UpdateCustomerTrigger]    Script Date: 22.05.2016 10:40:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[UpdateCustomerTrigger]
ON [dbo].[Customer]
FOR UPDATE
AS 
BEGIN
    UPDATE Customer SET UpdatedUtc = GETDATE()
    FROM INSERTED
    WHERE inserted.id=Customer.Id

    INSERT INTO [dbo].[AuditTable]
    SELECT
    StateBefore = 
    (
        SELECT *
        FROM deleted [Customer]
        WHERE [Customer].Id = cust.Id
        FOR XML AUTO
    ),
    [StateAfter] =(
        SELECT *
        FROM inserted [Customer]
        WHERE [Customer].Id = cust.Id
        FOR XML AUTO
    )
    FROM inserted cust
END