1

我有一个表,我想在其中存储对数据库执行的所有插入、更新和删除操作。该表应如下所示:

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

等等...

在每个表上使用触发器,如何构造操作查询?假设您并不总是知道表中导致触发器的列,因为您可能会在以后将列添加到表中,并且不希望返回并重建触发器。

这可能是它的开始:

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
4

0 回答 0