I use the following SQL to concatenate several database columns from one table into one column in the result set:
SELECT (field1 + '' + field2 + '' + field3) FROM table1
When one of the fields is null I got null result for the whole concatenation expression. How can I overcome this?
The database is MS SQL Server 2008. By the way, is this the best way to concatenate database columns? Is there any standard SQL doing this?
Just Cast Column As Varchar(Size)
If both Column are numeric then use code below.
Example:
What will be the size of
col3
it will be 40 or something elseIf you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:
http://www.codeproject.com/KB/database/DataCrunching.aspx
If you were using SQL 2012 or above you could use the CONCAT function:
NULL fields won't break your concatenation.
@bummi - Thanks for the comment - edited my answer to correspond to it.
Use ISNULL to overcome it.
Example:
This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.
If both Column are numeric Then Use This code
Example:
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..