How to concatenate a field from multiple rows into a single text string in SQL Server?

SQL Buddy
SQL Buddy
2 Points
1 Posts

How to concatenate a field from multiple rows into a single text string in SQL Server?

Consider a database table 'User' holding names, with three rows as:

  1. Peter
  2. Paul
  3. Mary

I want query result as comma separated string as 

Peter,Paul,Mary

Views: 583
Total Answered: 2
Total Marked As Answer: 0
Posted On: 23-Jan-2023 22:57

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Use FOR XML PATH clause as:

SELECT Name +',' FROM User FOR XML PATH('')
Posted On: 26-Jan-2023 05:29
Smith
Smith
2890 Points
78 Posts
         

You can concatenate the values of a field from multiple rows into a single text string in SQL Server by using the FOR XML PATH and STUFF functions. Here's an example of how to do it:

DECLARE @StringVariable VARCHAR(MAX)

SELECT @StringVariable = STUFF((SELECT ', ' + names
                                FROM User
                                FOR XML PATH('')), 1, 2, '')

SELECT @StringVariable AS ConcatenatedString

In this example, the FOR XML PATH function is used to concatenate the values of the names field, separated by a comma and a space. The STUFF function is used to remove the first two characters (', ') from the concatenated string. The result is then stored in the @StringVariable variable and can be returned as the ConcatenatedString field.

 

Posted On: 12-Feb-2023 08:16
 Log In to Chat