Read + Write + Report
Home | Start a blog | About Orble | FAQ | Blogs | Writers | My Orble | Login

The Many Uses of Coalesce in SQL Server

July 7th 2008 06:30
The Many Uses of Coalesce in SQL Server


Problem
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.



Solution
Let's start with the documented use of coalesce. According to MSDN, coalesce returns the first non-null expression among its arguments.

For example,

SELECT COALESCE(NULL, NULL, NULL, GETDATE())


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

SELECT Name
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')

you will come up with a standard result set such as this.

Name
1.Human Resources
2.Finance
3.Information Services
4.Facilities and Maintenance
5.Executive


If you want to pivot the data you could run the following command.

DECLARE @DepartmentName VARCHAR(1000)

SELECT @DepartmentName = COALESCE(@DepartmentName,'') Name ';'
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')

SELECT @DepartmentName AS DepartmentNames

and get the following result set.

DepartmentNames
1.Human Resources;Finance;Information Services;Facilities and Maintenance;Executive


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.


DECLARE @SQL VARCHAR(MAX)

CREATE TABLE #TMP
(Clmn VARCHAR(500),
Val VARCHAR(50))

SELECT @SQL=COALESCE(@SQL,'') CAST('INSERT INTO #TMP Select ''' TABLE_SCHEMA '.' TABLE_NAME '.'
COLUMN_NAME ''' AS Clmn, Name FROM ' TABLE_SCHEMA '.[' TABLE_NAME
'];' AS VARCHAR(MAX))
FROM INFORMATION_SCHEMA.COLUMNS
JOIN sysobjects B ON INFORMATION_SCHEMA.COLUMNS.TA BLE_NAME = B.NAME
WHERE COLUMN_NAME = 'Name'
AND xtype = 'U'
AND TABLE_SCHEMA = 'Person'

PRINT @SQL
EXEC(@SQL)

SELECT * FROM #TMP
DROP TABLE #TMP


here is the result set.

Clmn Val
260 Person.Country.Region.Name Virgin Islands,US
261 Person.Country.Region.Name Wallis and Futuna
262 Person.Country.Region.Name Yemen
263 Person.Country.Region.Name Zambia
264 Person.Country.Region.Name Zimbabwe
265 Person.State.Province.Name Ain
.
.
.
.
271 Person.Country.Region.Name Alpes



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.


DECLARE @SQL VARCHAR(8000)

SELECT @SQL=COALESCE(@SQL,'') 'Kill ' CAST(spid AS VARCHAR(10)) '; '
FROM sys.sysprocesses
WHERE DBID=DB_ID('AdventureWorks')

PRINT @SQL --EXEC(@SQL) Replace the print statement with exec to execute

will give you a result set such as the following.

Messages
Kill 52;Kill53;Kill54
72
Vote
Add To: del.icio.us Digg Furl Spurl.net StumbleUpon Yahoo


   

   

   


Add A Comment

To create a fully formatted comment please click here.


CLICK HERE TO LOGIN | CLICK HERE TO REGISTER

Name or Orble Tag
Home Page (optional)
Comments
Bold Italic Underline Strikethrough Separator Left Center Right Separator Quote Insert Link Insert Email
Notify me of replies
Notify extra people about this comment
Is this a private comment?
List the Email Addresses or Orble Tags of the people you would like to be notified about this comment


One per line max of 30

List the Email Addresses or Orble Tags of the people you would like to be notified about this private comment thread. Only the people in this list will be able to see or reply to your comment.


One per line max of 30

Your Name
(for the email going out to the above list, it can be different to your Orble Tag)
Your Email Address
(optional)
(required for reply notification)
Submit
More Posts
4 Posts
11 Posts
1 Posts
77 Posts dating from May 2008
Email Subscription
Receive e-mail notifications of new posts on this blog:
0

Siddharth sood's Blogs

37 Vote(s)
0 Comment(s)
1 Post(s)
84 Vote(s)
0 Comment(s)
2 Post(s)
37 Vote(s)
0 Comment(s)
1 Post(s)
50 Vote(s)
0 Comment(s)
1 Post(s)
29 Vote(s)
0 Comment(s)
1 Post(s)
76 Vote(s)
0 Comment(s)
2 Post(s)
169 Vote(s)
0 Comment(s)
4 Post(s)
213 Vote(s)
2 Comment(s)
5 Post(s)
26 Vote(s)
0 Comment(s)
1 Post(s)
25 Vote(s)
0 Comment(s)
1 Post(s)
Moderated by Siddharth sood
Copyright © 2006 2007 2008 On Topic Media PTY LTD. All Rights Reserved. Design by Vimu.com.
On Topic Media ZPages: Sydney |  Melbourne |  Brisbane |  London |  Birmingham |  Leeds     [ Advertise ] [ Contact Us ] [ Privacy Policy ]