Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Coalesce in your SQL Server Stored Procedures

There are so many built-in functions and keywords in SQL Server to help our applications perform and the coding is so easy that many get lost in the breadth of everyday needs. A few months ago I came across a function that I did not recall seeing before, Coalesce.

Often we need to handle situations where we may have null values and the IsNull function just will not suffice. Coalesce is a function that offers a little more functionality than the IsNull function because you can pass it a series of values and it will return the first non-null value in the list. IsNull takes two parameters, the value you want to check and a default value if the first value is null.

The Coalesce function is equivalent to a CASE statement, with the ELSE case returning NULL. While the IsNull function returns a default value when it is passed a null value, the Coalesce does not. You could embed a Coalesce function inside an IsNull function to get a default value for null.

The example in the documentation shows how you could return the first non-null value of a commission structure for an employee. The following example returns the first Id of the college associated with the record.

COALESCE(CollegeId, JrCollegeId, ComunityCollegeId)

So if the CollegeId is null and the JrCollegeId has a value the JrCollegeId value is returned.

I hope you find this useful and can use it in your stored procedures one day!

Posted: Monday, September 24, 2007 4:42 AM

by Chris Love
Filed under: ,

Comments

Chris Love's Official Blog - Professional ASP.NET said:

Dealing with Null values (nothing in VB.NET) is a common problem for programmers of any stripe. Null

# July 13, 2008 10:32 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS