Concatenate column values from multiple rows into a single column in SQL Server

I have created a simple table to demonstrate how to concatenate the values from multiple rows in to one column.

CREATE TABLE #tblProduct (product_Id INT IDENTITY(1,1), product_name VARCHAR(10))

Insert some sample records in to this temporary table

INSERT INTO #tblProduct (product_name) VALUES('AAA')
INSERT INTO #tblProduct (product_name) VALUES('BBB')
INSERT INTO #tblProduct (product_name) VALUES('CCC')
INSERT INTO #tblProduct (product_name) VALUES('DDD')
INSERT INTO #tblProduct (product_name) VALUES('EEE')
INSERT INTO #tblProduct (product_name) VALUES('FFF')
INSERT INTO #tblProduct (product_name) VALUES('GGG')

Once you have populated the table with data, Run this query to get the row values in to one column.

DECLARE @productarr VARCHAR(8000) SET @productarr = '' SELECT @productarr = @productarr + '"' + CAST(product_Id AS VARCHAR) + '",' FROM #TBLPRODUCT ORDER BY product_Id
SELECT LEFT(@productarr,LEN(@productarr)-1)
DROP TABLE #tblProduct

That’s all you have done with the job

7 comments:

  1. All life demands struggle. Those who have everything given to them become lazy, selfish, and insensitive to the real values of life. The very striving and hard work that we so constantly try to avoid is the major building block in the person we are today. See the link below for more info.

    values @
    www.inspgift.com

    ReplyDelete
  2. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


    enola
    www.edupdf.org

    ReplyDelete
  3. Excellent blog post. I like the information that I get from this site.

    www.joeydavila.net

    ReplyDelete
  4. This is an article well worth learning, there is much to learn from, each of us should write more articles to their own information available to everyone to know that we can learn from each other, with the progress.

    Jenna
    www.imarksweb.org

    ReplyDelete
  5. We all need challenges in our life to keep motivated. I really had a great time scanning and reading your blog site and i was so amazed with your great artwork. I do hope you could inspire more readers. You can also visit my site for some interesting stuff.

    n8fan.net

    www.n8fan.net

    ReplyDelete
  6. Thanks for sharing your article and for giving us the chance to read it. It is very helpful and encouraging. Visit my site too.

    triciajoy.com

    www.triciajoy.com

    ReplyDelete