Last Sunday we saw how we can intercept new and old values from the row during insert/update/delete operations with OUTPUT clause. Even if it’s very powerful mechanism, there is one very important limitation. You can intercept only values from the row of the table that gets updated.
So, for example, if you have:
you can intercept the values from DestTable rows but you cannot get any values from SourceTable rows.
In SQL Server 2005 you’re stuck. Fortunately SQL Server 2008 has the solution for that problem – Merge operator.
So what is MERGE? In short – it’s insert/update/delete operator – all-in-one. Assuming you have a source table and need to do that batch update based on another table. So you need to delete rows on the source table that do not exist in the second table, insert new rows from the second table and update modified rows. Let’s see that:
So Refresh process should delete row with ID = 1 from the SourceTable, insert row with ID = 7 and update rows with ID = 3 and 6.
Let’s see that in action. SQL 2005 approach is to use separate statements:
As you can see it works. But there are 3 statements. Longer locking, side effects based on the isolation levels, etc etc etc.
Now let’s do the same thing with MERGE operator:
As you can see – one operator and that’s all. Very useful and very very very convinient. But that’s not all – let’s see what can be done with the OUTPUT clause there:
It’s not only allowing you to capture old and new version of the row, it also allows to capture ACTION and the field from the Source (DataTable). The last one cannot be done with the regular insert/update/delete statements.
We will see what benefits will it give us next Sunday.
The code can be downloaded here