Hello guys and welcome to Code2Night. In the article, we will see how to convert Multiple Rows to a Comma-Separated Value in SQL Server
In SQL Server, there are times when we encounter scenarios where we need to combine multiple rows into a single comma-separated value. This can be useful when we want to retrieve data from a table in a format that is easier to process or display. Thankfully, SQL Server provides us with several techniques to achieve this.
DECLARE @Table1 TABLE(ID INT, Value INT) INSERT INTO @Table1 VALUES (1,100),(1,200),(2,300),(2,400) 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
Here is the output for Multiple rows to one comma-separated value in SQL Server