当其中一个值为空(非空)时合并 3 列删除多余的 space
Combine 3 Column when one of the value is empty( not null) remove extra space
数据
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 )
谢谢
考虑 Concat() 如果 2012+
正如您在 col2 中看到的那样...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
Returns
5121 w river road
5512 pine road -- No Extra Space
1313 mocking bird lane -- NULLs handled
问题是你有三种情况
- 空
- 长度 = 0
- 长度 > 0
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 版本在 NULL
和 length > 0
上运行正常,但在 length = 0
上运行失败
数据
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 )
谢谢
考虑 Concat() 如果 2012+
正如您在 col2 中看到的那样...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
Returns
5121 w river road
5512 pine road -- No Extra Space
1313 mocking bird lane -- NULLs handled
问题是你有三种情况
- 空
- 长度 = 0
- 长度 > 0
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 版本在 NULL
和 length > 0
上运行正常,但在 length = 0