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

4 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. Excellent blog post. I like the information that I get from this site.

    www.joeydavila.net

    ReplyDelete
  3. 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
  4. Aw, this was a very nice post. In idea I would like to put in writing like this additionally – taking time and actual effort to make a very good article… but what can I say… I procrastinate alot and not at all appear to get one thing done. free online casino slots

    ReplyDelete