Many times people come across the Coalesce function and think that it is just a more powerful form of ISNULL. In actuality, I have found it to be one of the most useful functions with the least documentation. In this tip, I will show you the basic use of Coalesce and also some features you probably never new existed.
Let's start with the documented use of coalesce. According to MSDN, coalesce returns the first non-null expression among its arguments.
will return the current date. It bypasses the first NULL values and returns the first non-null value.
Using Coalesce to Pivot
If you run the following statement against the AdventureWorks database
you will come up with a standard result set such as this.
If you want to pivot the data you could run the following command.
and get the following result set.
Using Coalesce to Execute Multiple SQL Statements
Once you can pivot data using the coalesce statement, it is now possible to run multiple SQL statements by pivoting the data and using a semicolon to separate the operations. Let's say you want to find the values for any column in the Person schema that has the column name "Name". If you execute the following script it will give you just that.
here is the result set.
My personal favorite is being able to kill all the transactions in a database using three lines of code. If you have ever tried to restore a database and could not obtain exclusive access, you know how useful this can be.
will give you a result set such as the following.
- Whenever I think I may need a cursor, I always try to find a solution using Coalesce first.
- I am sure I just scratched the surface on the many ways this function can be used. Go try and see what all you can come up with. A little innovative thinking can save several lines of code.
Last Update: 6/17/2008
About the author
View all my tips