Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Select returning NULL

Author  Topic 

macca
Posting Yak Master

146 Posts

Posted - 2012-08-28 : 11:30:09
I am doing a Select of two fields and merging them into one field.
Select [Column1] + ' ' + [Column2] AS Column3

If Column1 and Column2 both contain data then Column3 is returned with the combined value.
But if 1 or 2 does not contain data NULL is returned to Column 3 for that record.

Anyone know what I'm doing wrong?

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-08-28 : 11:34:37
You are not doing anything really "wrong", that is the expected behavior. NULL + anything else is NULL. To get around that use COALESCE or ISNULL like this:
Select COALESCE([Column1],'') + ' ' + COALESCE([Column2],'') AS Column3
COALESCE function picks the first argument if that is not null, and the second one if the first happens to be null.
Go to Top of Page

macca
Posting Yak Master

146 Posts

Posted - 2012-08-29 : 05:35:40
Thanks, That did teh trick.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-29 : 13:16:49
you can change that default behaviour using the concat null yields null setting but its highly unrecommended as it can cause undesirable behaviour sometimes

http://msdn.microsoft.com/en-us/library/ms176056.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -