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

时间:2017-04-23 14:59:34

标签: sql sql-server function tsql

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

enter image description here

转换为:" 68,74,58,64,67"

2 个答案:

答案 0 :(得分:2)

使用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 |
+----------------+

答案 1 :(得分:1)

您可以使用stuff和xml路径来连接第一个逗号后的连接和选择数据。

With 

Member [Tb Supplier].[City].[B2A] as
Aggregate([Tb Supplier].[City].&[B], [Tb Consumer].[City].&[A])

Member [Tb Supplier].[City].[A2B] as
Aggregate([Tb Supplier].[City].&[A], [Tb Consumer].[City].&[B])

Select 
    {[Tb Supplier].[City].[A2B],[Tb Supplier].[City].[B2A]} on 0
From [Cube]
Where ([Measures].[Quantity - Transactions])

你的桌子:

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