Concatenating all the rows of a column using the coalesce function

Hi,

 

A few days ago one of my friend asked me about how to concatenate all the rows in a table or some of the rows in a table in a string in the SQL Server. The first idea was to create a user defined function, which would take the column name and return the concatenated value of all the rows in that column.

 

But a little later I found there is an inbuilt function in TSQL for the same. We can use the coalesce function to get the result of all the rows in a column in TSQL. Here is an example of the same

 

SELECT COALESCE(@column1 + ',', '') + column1
FROM Table1 

 

So if table1 had following records

 

Column1

aa

bb

cc

dd

 

The result of the query will be aabbccdd

 

So

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 1/23/2008 10:10:16 AM

Hi Vikram,

Sometimes being lazy, I never gave a try to understand coalesce command. Your article is simple and nice!

thanks
Ganesh

Posted on 1/28/2008 8:44:31 PM

You can also use the ISNULL command too:

SELECT @emailList = ISNULL(@emailList + '; ' ,'') + emailAddress
FROM Table

Note: this example separates with semi-colon.

Posted on 2/12/2008 10:49:30 PM

One of the limitation of COALESCE is that it will return the thing in varchar2 that means is the string is too large then it will not work

Posted on 5/23/2008 11:38:20 PM

Check out coalesce functionality

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia