在连接列之后插入换行符返回SQL查询返回,同时跳过NULL值

时间:2017-03-20 10:29:50

标签: sql sql-server concatenation

我希望将多个列连接在一起,并将每个列的返回值与换行符分开,并考虑NULL值。

例如,我有以下数据表([dbo].[Address]):

Name         Address_line1    Address_line2   Address_line 3   Postcode
Mr Smith     1 Smith Street   NULL            Ireland          AB1 1CD
Mr Jones     1 Jones Road     Wales           NULL             EF2 3GH
Mrs White    1 White Way      England         UK               NULL

我想返回以下内容:

Name         Address
Mr Smith     1 Smith Street,
             Ireland,
             AB1 1CD
Mr Jones     1 Jones Road,
             Wales,
             EF2 3GH
Mrs White    1 White Way,
             England,
             UK

我该怎么做?

5 个答案:

答案 0 :(得分:1)

您可以结合使用COALESCE()运算符和WITH T AS (SELECT 'Mr Smith' AS NAME, '1 Smith Street' AS Address_Line1, NULL AS Address_line2, 'Ireland' AS Address_Line3, 'AB1 1CD' AS PostCode UNION SELECT 'Mr Jones' AS NAME, '1 Jones Road' AS Address_Line1, 'Wales' AS Address_line2, NULL AS Address_Line3, 'EF2 3GH' AS PostCode UNION SELECT 'Mrs White' AS NAME, '1 White Way' AS Address_Line1, 'England' AS Address_line2, 'UK' AS Address_Line3, NULL AS PostCode ) SELECT NAME, ADDRESS_LINE1 + COALESCE(','+ CHAR(13)+CHAR(10) + Address_line2 , '') + COALESCE ',' + (CHAR(13)+CHAR(10) +Address_line3 ,'') + COALESCE(',' + CHAR(13)+CHAR(10) +POSTCODE,'') AS ADDRESS FROM T

NAME      
--------- --------------------------------------------
Mr Jones  1 Jones Road,
   Wales,
   EF2 3GH
Mr Smith  1 Smith Street,
   Ireland,
   AB1 1CD
Mrs White 1 White Way,
   England,
   UK

输出:

[End Date]>=[Start Date]

答案 1 :(得分:1)

你试过这个吗?

select name,
       replace(stuff( coalesce('[sep]' + address_line1, '') +
                      coalesce('[sep]' + address_line2, '') +
                      coalesce('[sep]' + address_line3, ''),
                      1, 5, ''
                    ), '[sep]', '
'
               )
. . .

答案 2 :(得分:0)

您可以使用CHAR(13)之类的

select Name, 
Address_line1 + ',' +char(13) + Address_line2 + ',' + char(13) + Address_line 3 as address 
from [dbo].[Address]

答案 3 :(得分:0)

SELECT 
name, 
CONCAT(
COALESCE(Address_line1,''), ', ', 
COALESCE(Address_line2,''), ', ', 
COALESCE(Address_line3,''), ', ', 
COALESCE(Postcode,'')
) AS address 
FROM table_name;

答案 4 :(得分:0)

我更喜欢使用带有Char(13)+ CHAR(10)的ISNULL():

SELECT 
Name 
, ISNULL(Address_line1 + ',' + CHAR(13)) + CHAR(10), '') + ISNULL(Address_line2 + ',' + CHAR(13)) + CHAR(10), '') + ISNULL(Address_line 3, '') as address 
from [dbo].[Address]