我找不到一种简单/通用的方法来注册审计表,在某些表上更改了列。
我尝试以这种方式在更新后使用触发器来做到这一点:
首先是审计表定义:
CREATE TABLE [Audit](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL default GETDATE(),
[IdTypeAudit] [int] NOT NULL, --2 for Modify
[UserName] [varchar](50) NULL,
[TableName] [varchar](50) NOT NULL,
[ColumnName] [varchar](50) NULL,
[OldData] [varchar](50) NULL,
[NewData] [varchar](50) NULL )
接下来是任何表中的 AFTER UPDATE 触发器:
DECLARE
@sql varchar(8000),
@col int,
@colcount int
select @colcount = count(*) from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable'
set @col = 1
while(@col < @colcount )
begin
set @sql=
'INSERT INTO Audit
SELECT 2, UserNameLastModif, ''MyTable'', COL_NAME(Object_id(''MyTable''), '+ convert(varchar,@col) +'), Deleted.'
+ COL_NAME(Object_id('MyTable'), @col) + ', Inserted.' + COL_NAME(Object_id('MyTable'), @col) + '
FROM Inserted LEFT JOIN Deleted ON Inserted.[MyTableId] = Deleted.[MyTableId]
WHERE COALESCE(Deleted.' + COL_NAME(Object_id('MyTable'), @col) + ', '''') <> COALESCE(Inserted.' + COL_NAME(Object_id('MyTable'), @col) + ', '''')'
--UserNameLastModif is an optional column on MyTable
exec(@sql)
set @col = @col + 1
end
问题
- 当我使用 exec 函数时,Inserted 和 Deleted 丢失了上下文
- 似乎 colnumber 它并不总是一个相关数字,似乎如果您创建一个包含 20 列的表,然后删除一个并创建另一个,最后一个有一个数字 > @colcount
我一直在为整个网络寻找解决方案,但我无法弄清楚
任何想法?
谢谢!