使用逗号SQL Server将int列表转换为字符串 [英] Convert int list to string with comma SQL Server
本文介绍了使用逗号SQL Server将int列表转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在SQL Server中使用逗号将int列表转换为带有字符串的字符串?
How convert a list of int to string with comma with function in SQL Server?
转换为:"68,74,58,64,67"
Convert to : "68,74,58,64,67"
推荐答案
使用 stuff()
,其中 select ...为xml路径('')
字符串连接方法.
create table t (ProductId int);
insert into t values (68) ,(74) ,(58) ,(64) ,(67);
select
ProductIds = stuff((
select ','+convert(varchar(10),ProductId)
from t
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'')
rextester演示: http://rextester.com/RZQF31435
rextester demo: http://rextester.com/RZQF31435
返回:
+----------------+
| ProductIds |
+----------------+
| 68,74,58,64,67 |
+----------------+
在SQL Server 2017+中,您可以使用 string_agg()
,根据Jeffry Schwartz的文章:
edit: In SQL Server 2017+, you can use string_agg()
, and the performance appears to be the same based on Jeffry Schwartz's article: Should I Replace My FOR XML PATH String Merges with String_agg?
这篇关于使用逗号SQL Server将int列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文