Merge two database columns into one result column

I use the following SQL to concatenate multiple database columns from one table to one column in the result set:

SELECT (field1 + '' + field2 + '' + field3) FROM table1

When one of the fields is null, I got a 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?

+33
sql sql-server-2008 concatenation
Jun 21 2018-11-11T00:
source share
7 answers

The standard SQL way to do this:

 SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1 

Example:

 INSERT INTO table1 VALUES ('hello', null, 'world'); SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1; helloworld 
+41
Jun 21 2018-11-11T00:
source share

If you used SQL 2012 or higher, you can use the CONCAT function:

 SELECT CONCAT(field1, field2, field3) FROM table1 

NULL fields will not violate your concatenation.

@bummi - Thanks for the comment - edited my answer to fit it.

+27
Sep 11 '14 at 11:45
source share

The normal behavior with NULL is that any operation, including NULL, yields NULL ...

 - 9 * NULL = NULL - NULL + '' = NULL - etc 

To overcome this, use ISNULL or COALESCE to replace any NULL instances with something else.

 SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1 
+14
Jun 21 2018-11-11T00:
source share

If you have a problem with NULL values, use the COALESCE function to replace NULL with the value of your choice. Then your request will look like this:

 SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1 

http://www.codeproject.com/KB/database/DataCrunching.aspx

+4
Jun 21 2018-11-11T00:
source share

Use ISNULL to overcome it.

Example:

 SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1 

This will then replace your NULL content with an empty string, which will keep the concatenation operation from evaluating as a common NULL result.

+3
Jun 21 2018-11-11T00:
source share

If both columns are numeric, then use this code

Just Cast Column As Varchar (Size)

Example:

 Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table 
+1
Feb 29 '16 at 9:52
source share

Just Cast Column As Varchar (Size)

If both columns are numeric, use the code below.

Example:

 Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table 

What will be the size of col3 , it will be 40 or something else

+1
Nov 27 '17 at 6:34
source share



All Articles