Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma delimited list as a single string, T-SQL [duplicate]

My T-SQL query generates following result set

ID        Date 756 2011-08-29 756 2011-08-31 756 2011-09-01 756 2011-09-02 

How can I convert like this

ID                Date 756 2011-08-29, 2011-08-31, 2011-09-01, 2011-09-02 

Any suggestion would be appreciated.

like image 759
poshan Avatar asked Aug 14 '13 15:08

poshan


People also ask

How do you remove duplicates from a comma separated string in SQL?

Solution 1. Available in SQL Server 2016 and later. -- Sort the values: SELECT value FROM STRING_SPLIT(@temp, ',') ORDER BY value; -- Remove duplicates: SELECT DISTINCT value FROM STRING_SPLIT(@temp, ',');

How get data from comma separated values in SQL?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.


1 Answers

You could use FOR XML PATH and STUFF to concatenate the multiple rows into a single row:

select distinct t1.id,   STUFF(          (SELECT ', ' + convert(varchar(10), t2.date, 120)           FROM yourtable t2           where t1.id = t2.id           FOR XML PATH (''))           , 1, 1, '')  AS date from yourtable t1; 

See SQL Fiddle with Demo

like image 109
Taryn Avatar answered Sep 20 '22 17:09

Taryn