Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int list to string with comma SQL Server

How convert a list of int to string with comma with function in SQL Server?

enter image description here

Convert to : "68,74,58,64,67"

like image 556
habiat Avatar asked Dec 03 '25 14:12

habiat


1 Answers

using the 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 demo: http://rextester.com/RZQF31435

returns:

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

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?

like image 174
SqlZim Avatar answered Dec 06 '25 06:12

SqlZim