Skip to content
Advertisement

T-SQL Trigger – Audit Column Change

Given a simple table, with an ID what is the correct way to audit a column being changed. I am asking after looking after various answers which seem not to be working.

Here is what I have:

What I see is thousands of examples where Tbl_Old_ColumnValue = Tbl_New_ColumnValue , which is not what I want.

I would expect to run:

But this returns no results.

In order to get results of columns that actually changed, I need to run a very expensive query:

Results:

But that doesn’t produce what I expect:

Oddly, If I modify the column directly via SSMS using:

I see what I expect from my trigger:

What am I doing wrong?

Also, how do I eliminate auditing of row where update(ColumnName) is actually false. IE, the ColumnName (even if being set) is not audit when it is being set to the previous/old value.

Advertisement

Answer

update(ColumnName) doesn’t mean that the value has changed, just that that column was involved in the insert/update – and it will always be involved in an insert. You need to compare the old and new values using inserted and deleted e.g.

You can potentially simplify the null check using coalesce and a suitable value which will never actually occur in your data.

The documentation is actually pretty good on all this.

And if the column is not always included in an update, then the update(ColumnName) test is still worth doing because it speeds up the trigger, and triggers should be as fast as possible. Personally I short circuit out early e.g. if not update(ColumnName) return;

Obviously you need to adapt that logic to handle all the columns you are auditing.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement