Using OUTPUT clause to track changes
October 1, 2014 2 Comments
Whenever something changes in a database, you would like to know what has changed. This change might brake your database or application later, so all schema or server changes are monitored. But how about data changes? Do you monitor those? You don’t have to feel bad if you don’t, because most people don’t track those changes. But you can track these changes in a very easy way, by using the output clause in your query. Let’s take a look at how that works.
Create resources
As example, let’s take a look at a bank account. If you have a bank account, there’s some money in it, and you spend money which will be subtracted from your account balance. First of all, let’s make two tables: one for the account balance, and one for logging the changes:
CREATE TABLE #Account (ID INT IDENTITY(1,1), Balance FLOAT) CREATE TABLE #Logging (DEL_ID INT, DEL_Balance FLOAT, UPD_ID INT, UPD_Balance FLOAT, Balance_Difference FLOAT)
To keep it simple, the account table has just one column, and that column contains the current balance of the account. Let’s insert a balance to start with:
INSERT INTO #Account (Balance) VALUES (250.25)
If we run an update query now, the account balance will change. But do we still know what the original balance was? Not without logging. So let’s see how the output clause can change this:
UPDATE #Account SET Balance = 125.00 OUTPUT Deleted.ID, Deleted.Balance, Inserted.ID, Inserted.Balance, Inserted.Balance - Deleted.Balance INTO #Logging
The balance table now only contains the new value. But by using the output clause, that logged the changes we made, we can check the logging table, and find the old value. When looking at the output clause, you can use the temporary objects called Deleted and Inserted. The Deleted table contains the old values (before the change), and the Inserted contains the new values (the values after the change). When checking the logging table, you’ll see both the old and the new values:
So as you can see, the logging table contains both the old and the new version of the record. And this not only works for update queries, but also for Inserts, Deletes and Merge-statements. This gives you the opportunity to log changes in the queries you think need it. Just think about what you want to log, create a log table, and add an output clause to your query. It’s not always the case, but with this, it’s as easy as that.
If you want to read more about CRUD, don’t forget to check out these blog posts:
– Julie Koesmarno: On sabbatical
– Mickey Stuewe: Going Beyond The INSERT Statement
– Chris Yates: C-R-U-D The Basics
Pingback: BPOTW 2014-10-03 | SQL Notes From The Underground
Pingback: SQL Server