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

Convert to : "68,74,58,64,67"
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With