concatenate two database columns into one resultset column

后端 未结 7 2072
独厮守ぢ
独厮守ぢ 2020-11-28 10:00

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

SELECT (field1 + \'\' + field2 + \'\' + field

相关标签:
7条回答
  • 2020-11-28 10:06

    If you were using SQL 2012 or above you could use the CONCAT function:

    SELECT CONCAT(field1, field2, field3) FROM table1
    

    NULL fields won't break your concatenation.

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

    0 讨论(0)
  • 2020-11-28 10:06

    If both Column 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
    
    0 讨论(0)
  • 2020-11-28 10:08

    If 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:

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

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

    0 讨论(0)
  • 2020-11-28 10:12

    Normal behaviour with NULL is that any operation including a NULL yields a NULL...

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

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

    SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
    
    0 讨论(0)
  • 2020-11-28 10:14

    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 preserve the concatentation operation from evaluating as an overall NULL result.

    0 讨论(0)
  • 2020-11-28 10:21

    The SQL standard way of doing this would be:

    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
    
    0 讨论(0)
提交回复
热议问题