Wednesday, August 24, 2005

COALESCE Function replace NULL values

One of those rarely used (and easily forgotten) functions that's listed under 'best practise'. This is a handy function for replacing the NULL value of a column or variable with a DEFAULT value within calculations and formulas.

Not of course to be used within large SELECT statements to replace NULL values within a column due to performance issues.

USE Northwind

DECLARE @caol_tmp INT

--NULL value
SELECT @caol_tmp 'caol_tmp'

--with coalesce
SELECT COALESCE(@caol_tmp,2005) 
        AS'caol_tmp'

--causes an error, must be of the same type
--SELECT COALESCE(@caol_tmp,'string value') 
--      AS 'caol_tmp'

References

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ca-co_9dph.asp

1 Comments:

At 7:45 PM, Blogger Jeff Skee said...

COALESCE rocks! Thanks, this post helped me.

 

Post a Comment

<< Home