Skip to content
Advertisement

How to concat all the entries of one column [SQL]

As the title states, with the following SQL query:

I get the following result:

Question: how to modify the query so that all the names are to be displayed in a row, so that they can be later used an array.

What I tried: FOR XML, STUFF – doesn’t work

Expected result:

Advertisement

Answer

If you are using SQL Server you can try this:

Check this on Fiddle: http://sqlfiddle.com/#!18/6ab0b3/6

Or may be an easy way using COALESCE that combines the multiple rows in single row separated by Comma separated values based on parameters passed:

Check this on fiddle: http://sqlfiddle.com/#!18/36112/2

Also, I am giving the screenshots for you to easily understand the steps if something goes wrong with the above screenshots.

Please note: In the above process, neither I have taken any PRIMARY KEY nor I am setting its auto-increment, but in the upcoming explanation I have used PRIMARY KEY as I have written everything in SSMS (Sql Server Management Studio)

Here is the schema for sample tblStudent table with PRIMARY KEY and auto increment set as you can see below:

enter image description here

Next enter some dummy values in it

enter image description here

finally write our query.

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement