Go to home page mail me! RSS Feed

Concatenating multiple rows into single column in SQL Server

Tuesday, September 29, 2009 3:44 PM

Sometimes you need to return a single column that contains values that are comma separated or pipe separated or what ever floats your boat from a multiple row result set, a perfect example is returning the category id’s for a product that could be in one of more categories but you don’t want to return multiple rows with duplicate information.

There are two ways of doing this or two that I know of – meaning simple enough.

1. The COALESCE method, which is probably the most common. This method works by tricking the coalesce function into doing something else, COALESCE is very similar to ISNULL except it can take in more than 2 arguments.

select @results = COALESCE(cast(ProductCategoryId as varchar)+',','')
    from ProductCategory where ProductId = 24

 

2. Using the FOR XML PATH expression which works very well and its probably my preferred method because it takes order into consideration. If you use the FOR XML PATH without specifying the column name, you get concatenation – cool trick huh?

select cast(ProductCategoryId as varchar) + ',' from Productcategory
            where ProductId = 24 for xml path('')

Have fun!!!

DotNetKicks Image

Your Comments.

  • # re: Concatenating multiple rows into single column in SQL Server

    Gravatarselect @results = COALESCE(@results + ',', '') + cast(ProductCategoryId as varchar) from Productcategory where ProductId = 24

    Left by Anonymous Tipper at 10/22/2009 7:32 AM
  • # re: Concatenating multiple rows into single column in SQL Server

    GravatarThanks Rydal and Anonymous Tipper, Excellent helpful and works first time

    KISS solutions as they should be...

    Left by silicon.monochromatic at 12/8/2009 12:14 PM
  • # re: Concatenating multiple rows into single column in SQL Server

    GravatarExactly what I need 10x, it worked like a charm

    Left by Vinoth at 1/20/2010 6:36 AM

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 2 and 3 and type the answer here:

Preview Your Comment.

 
Next entries »