当其中一个值为空(非空)时合并3列,删除多余的空格

时间:2017-04-05 17:16:07

标签: sql trim coalesce

数据

col1    col2    col3 
5121     w        river road 
5512     empty    pine road 

查询1

Select LTRIM(ISNULL(Col1+' ','')+ ISNULL(col2+' ', '') + ISNULL(col3+' ','') as col4 from ...

查询2

Select LTRIM(COALESCE(Col1+' ','')+ COALESCE(col2+' ', '') + COALESCE(col3+' ','') as col4 from ...

两个结果我得到这个值

5121 w river road ( this looks good ) 
5512  pine road ( i get extra space for col 2 )

谢谢

2 个答案:

答案 0 :(得分:4)

问题是你有三个案例

  • NULL
  • 长度= 0
  • 长度> 0

DEMO

CREATE TABLE Table1
    ([col1] varchar(5), [col2] varchar(5), [col3] varchar(20))
;

INSERT INTO Table1
    ([col1], [col2], [col3])
VALUES
    ('5121', 'w', 'river road'),
    ('5512', null, 'pine road'),
    ('3333', '', 'death valley')
;

SELECT COALESCE(CASE WHEN col1 = '' THEN '' ELSE col1 + ' ' END, '')  + 
       COALESCE(CASE WHEN col2 = '' THEN '' ELSE col2 + ' ' END, '')  + 
       COALESCE(CASE WHEN col3 = '' THEN '' ELSE col3 + ' ' END, '')        

FROM Table1  

<强>输出

原始OP和Jhon版本可以与NULLlength > 0一起使用,但在length = 0

时失败

enter image description here

答案 1 :(得分:2)

如果2012 +

,请考虑 Concat()

正如你可以看到col2 ... null+' '将导致null,好消息是concat()表示空值为''

Declare @YourTable table (col1 varchar(50),col2 varchar(50),col3 varchar(50))
Insert Into @YourTable values
('5121','w', 'river road'),
('5512','','pine road'),  
('1313',null,'mocking bird lane')

Select concat(nullif(col1,'')+' ',nullif(col2,'')+' ',nullif(col3,''))
 From  @YourTable

<强>返回

5121 w river road
5512 pine road           -- No Extra Space
1313 mocking bird lane   -- NULLs handled