使用逗号将int列表转换为字符串SQL Server

问题描述:

如何将int列表转换为带有SQL Server中函数的逗号的字符串?到使用逗号将int列表转换为字符串SQL Server

enter image description here

转换: “68,74,58,64,67”

+6

Google:“sql server aggregate string concat” –

使用stuff() with select ... for xml path ('') method of string concatenation

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

回报:

+----------------+ 
| ProductIds | 
+----------------+ 
| 68,74,58,64,67 | 
+----------------+ 
+0

在DVD上看着侵略者Zim ......很多人大叫。 –

+0

@JohnCappelletti我通过保留我的sql小写来平衡它^^^ – SqlZim

您可以使用串联和选择数据的东西,XML路径从第一个逗号后..

select distinct stuff((select ',' + convert(char(2), productid) from #yourproductid for xml path('')),1,1, '') 
    from #yourproductid 

你表:

create table #yourproductid(productid int) 

insert into #yourproductid (productid) values (68),(74),(58),(64),(67)