Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple rows to one comma-separated value in Sql Server [duplicate]

I want to create a table valued function in SQL Server, which I want to return data in comma separated values.

For example table: tbl

ID | Value ---+-------  1 | 100  1 | 200  1 | 300       1 | 400  

Now when I execute the query using the function Func1(value)

SELECT Func1(Value)  FROM tbl  WHERE ID = 1 

Output that I want is: 100,200,300,400

like image 371
Sanjeev Singh Avatar asked Feb 13 '14 17:02

Sanjeev Singh


People also ask

How do you convert rows to comma separated values?

Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)

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

Solution 1 -- Sort the values: SELECT value FROM STRING_SPLIT(@temp, ',') ORDER BY value; -- Remove duplicates: SELECT DISTINCT value FROM STRING_SPLIT(@temp, ',');


1 Answers

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT) INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400) 

Query

SELECT  ID        ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]          FROM @Table1           WHERE ID = t.ID          FOR XML PATH(''), TYPE)         .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output FROM @Table1 t GROUP BY ID 

Result Set

╔════╦═════════════════════╗ ║ ID ║     List_Output     ║ ╠════╬═════════════════════╣ ║  1 ║  100, 200, 300, 400 ║ ╚════╩═════════════════════╝ 

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT); INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);   SELECT ID , STRING_AGG([Value], ', ') AS List_Output FROM @Table1 GROUP BY ID; 

Result Set

╔════╦═════════════════════╗ ║ ID ║     List_Output     ║ ╠════╬═════════════════════╣ ║  1 ║  100, 200, 300, 400 ║ ╚════╩═════════════════════╝ 
like image 72
M.Ali Avatar answered Sep 18 '22 10:09

M.Ali