Joh*_*ika 15 t-sql sql-server string-concatenation
假设我在SQL Server中有这样的表格:
Id City Province Country
1 Vancouver British Columbia Canada
2 New York null null
3 null Adama null
4 null null France
5 Winnepeg Manitoba null
6 null Quebec Canada
7 Seattle null USA
Run Code Online (Sandbox Code Playgroud)
如何获取查询结果,以便该位置是由","分隔的城市,省和国家的串联,省略空值.我想确保没有任何尾随逗号,前面的逗号或空字符串.例如:
Id Location
1 Vancouver, British Columbia, Canada
2 New York
3 Adama
4 France
5 Winnepeg, Manitoba
6 Quebec, Canada
7 Seattle, USA
Run Code Online (Sandbox Code Playgroud)
Aar*_*and 36
我认为这可以解决我在其他答案中发现的所有问题.无需测试输出的长度或检查前导字符是否为逗号,不用担心连接非字符串类型,当其他列(例如邮政编码)不可避免地添加时,复杂性没有显着增加...
DECLARE @x TABLE(Id INT, City VARCHAR(32), Province VARCHAR(32), Country VARCHAR(32));
INSERT @x(Id, City, Province, Country) VALUES
(1,'Vancouver','British Columbia','Canada'),
(2,'New York' , null , null ),
(3, null ,'Adama' , null ),
(4, null , null ,'France'),
(5,'Winnepeg' ,'Manitoba' , null ),
(6, null ,'Quebec' ,'Canada'),
(7,'Seattle' , null ,'USA' );
SELECT Id, Location = STUFF(
COALESCE(', ' + RTRIM(City), '')
+ COALESCE(', ' + RTRIM(Province), '')
+ COALESCE(', ' + RTRIM(Country), '')
, 1, 2, '')
FROM @x;
Run Code Online (Sandbox Code Playgroud)
SQL Server 2012添加了一个名为的新T-SQL函数CONCAT,但它在这里没有用,因为你仍然必须在发现的值之间包含逗号,并且没有设施可以做到这一点 - 它只是将值一起引导而没有选项分隔器.这样可以避免担心非字符串类型,但不允许您非常优雅地处理空值与非空值.
Kev*_*vin 10
select Id ,
Coalesce( City + ',' +Province + ',' + Country,
City+ ',' + Province,
Province + ',' + Country,
City+ ',' + Country,
City,
Province,
Country
) as location
from table
Run Code Online (Sandbox Code Playgroud)
这是一个难题,因为逗号必须介于两者之间:
select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '')
from t
Run Code Online (Sandbox Code Playgroud)
看起来它应该可以工作,但是我们可以在最后得到一个多余的逗号,例如当 country 为 NULL 时。所以,它需要更复杂一点:
select id,
(case when right(val, 2) = ', ' then left(val, len(val) - 1)
else val
end) as val
from (select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '') as val
from t
) t
Run Code Online (Sandbox Code Playgroud)
没有很多中间逻辑,我认为最简单的方法是在每个元素上添加一个逗号,然后在最后删除任何多余的逗号。