I can't find an easy/generic way to register to an audit table the columns changed on some tables.
I tried to do it using a Trigger on after update in this way:
First of all the Audit Table definition:
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 )
Next a trigger on AFTER UPDATE in any table:
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
The problems
- Inserted and Deleted lost the context when I use the exec function
- Seems that colnumber it isn't always a correlative number, seems if you create a table with 20 columns and you delete one and create another, the last one have a number > @colcount
I was looking for a solution for all over the net but I couln't figure out
Any Idea?
Thanks!
@Santiago : If you still want to write it in dynamic SQL, you should prepare all of the statements first then execute them. 8000 characters may not be enough for all the statements. A good solution is to use a table to store them.
Then replace the line
exec(@sql)
withINSERT INTO #stmt (SQL) VALUES (@sql);
Then exec each row.
Remember to use sys.columns for the column loop (I shall assume you use SQL 2005/2008).
Remove line 4
@colcount int
and the proceeding comma. Remove Information schema select.