If you are updating multiple rows in one statement, but only want to update a value in a column if a condition is satisfied, then you need to perform some sort of if logic inside your update. Here’s a straight forward way of doing this.
In the example below, I am just going to use 2 temp table variables. I’ll update the @SourceTable with the data from the @UpdateTable… but only where the UpdateFlag field is set to 1.
In the example above, you can see that the AnimalName is only updated when the UpdateFlag column is set to 1. The 2nd record “Cat” is not updated with the value “Cow” because it has a 0 for the UpdateFlag. This is done using a case statement on the SET operation. The example above is very simple. This case logic in the SET operation becomes much more helpful in more complex queries.
The OUTPUT clause is an amazing part of SQL Server that many people do not know about. As corny as it is, I still remember the day that I found it. I had been searching for the whole day trying to figure out how to get the identity values from a large amount of data that I just inserted in to the database. There had to be a way… right? After searching and searching, I gave up and just accepted that it is not possible… a few days later I found exactly what I was looking for… the OUTPUT clause.
The OUTPUT clause is a part of the query that will return data from before or after the operations is completed. Let’s say that you inserted data in to a table and you wanted the ID column values (which are auto-numbers). The OUTPUT clause gives you this information! It can work on INSERT, DELETE, UPDATE, and MERGE statements. I will take you through examples of each.
To access the data that is being altered in your sql statement, you need to use special column prefixes that SQL Server makes available to you. The two special prefixes are “inserted” and “deleted”. During an insert statement, the inserted prefix is available for you to use. During a delete statement, the deleted prefix is available to you. During the update and merge statements, both the deleted and inserted prefixes are available to you. In these cases, the deleted represents the data before it was changed and the inserted represents the data after it was changed.
One thing to note is that the data being outputted must go in to a table or table variable.
OUTPUT Clause On An INSERT Statement
-- Insert into the table and stick the resulting animal