我有一个表,我想存储对数据库执行的所有插入,更新和删除操作。表应如下所示:
ID Created Operation
1 2012-05-01 INSERT [SomeTable] (ID, Col1) VALUES (1, 'xyz')
2 2012-05-01 UPDATE [SomeTable] SET Col1 - 'abc' WHERE ID = 1
等等......
在每个表上使用触发器,如何构造Operation查询?假设您不会总是知道导致触发器的表中的列,因为您可能会在以后向表中添加列,并且不希望必须返回并重建触发器。
这可能是它的开始:
CREATE TRIGGER tr_MyTable_RowInserted ON MyTable
FOR INSERT
AS
DECLARE @columnList nvarchar(4000)
SET @columnList = NULL
SELECT @columnList = COALESCE(@columnList + ', ', '') + [name] FROM sys.columns WHERE Object_ID = Object_ID(N'MyTable')
print @columnList
-- now we have the columns, need to spit out the values that are in the trigger's inserted table
-- then we need to concatenate all of that into a single, syntactically correct SQL string