I have created trigger that inserts names of the columns changed (insert, update, delete) in the audit table.
I have problem when I update columns. Lets say I have a table dbo.TABLE with columns COL1, COL2, COL3.
Further, lets say that I only have one row:
COL1 | COL2 | COL3
---------------------------
value1 | value2 | value3
If my update statement looks like this:
Update dbo.TABLE set COL1 = 'test1', COL2 = 'test2';
In my audit table will be inserted:
UPDATED
-------
COL1, COL2
This is OK, but lets say I have same table dbo.TABLE with first values (value1, value2, value3).
If my update statement looks like this:
Update dbo.TABLE set COL1 = 'value1', COL2 = 'test2';
In my audit table same result will be inserted as above (COL1, COL2).
How can I alter my trigger so only updated column (COL2) will be inserted? I need some kind of statement that will check value of column before updating.
My trigger is too big to put all of it here, so I will only put part of the code that returns columns updated.
SELECT @idTable = T.id
FROM sysobjects P JOIN sysobjects T ON P.parent_obj = T.id
WHERE P.id = @@procid
SELECT @Columns_Updated = ISNULL(@Columns_Updated + ', ', '') + name
FROM syscolumns t
WHERE id = @idTable
AND CONVERT(VARBINARY,REVERSE(COLUMNS_UPDATED())) & POWER(CONVERT(BIGINT, 2), colorder - 1) > 0
This is original post from where I have taken the code: SQL Server Update Trigger, Get Only modified fields