OK. I’m doing an update on a single row in a table.
All fields will be overwritten with new data except for the primary key.
However, not all values will change b/c of the update.
For example, if my table is as follows:
TABLE (id int ident, foo varchar(50), bar varchar(50))
The initial value is:
id foo bar
-----------------
1 hi there
I then execute UPDATE tbl SET foo = 'hi', bar = 'something else' WHERE id = 1
What I want to know is what column has had its value changed and what was its original value and what is its new value.
In the above example, I would want to see that the column “bar” was changed from “there” to “something else”.
Possible without doing a column by column comparison? Is there some elegant SQL statement like EXCEPT that will be more fine-grained than just the row?
Thanks.
There is no special statement you can run that will tell you exactly which columns changed, but nevertheless the query is not difficult to write:
If you’re trying to actually do something as a result of these changes, then best to write a trigger:
(Of course you’d probably want to do more than this in a trigger, but there’s an example of a very simplistic action)
You can use
COLUMNS_UPDATEDinstead ofUPDATEbut I find it to be pain, and it still won’t tell you which columns actually changed, just which columns were included in theUPDATEstatement. So for example you can writeUPDATE MyTable SET Col1 = Col1and it will still tell you thatCol1was updated even though not one single value actually changed. When writing a trigger you need to actually test the individual before-and-after values in order to ensure you’re getting real changes (if that’s what you want).P.S. You can also
UNPIVOTas Rob says, but you’ll still need to explicitly specify the columns in theUNPIVOTclause, it’s not magic.