Translate

Wednesday 13 November 2013

How to merge more than 1 cell value with a comma in a single cell of a row in SQLServer.

Create table #temp1
    (
    Name varchar(10) 

    )

    Create table #temp2
    (
    Name varchar(10),
    Location varchar(100)
    )

    Insert into #temp1
    values ('h' ),('I' )

    Insert into #temp2
    values ('h','delhi'),
    ('h','Mumbai'),
    ('h','Hyderabad'),
    ('I','Chennai'),
    ('I','Delhi')

    Select *from #temp1
    Select *from #temp2



    select t.Name,
        STUFF((   SELECT ', ' +te.Location
            FROM #temp2 te
            WHERE T.Name = te.Name
            FOR XML PATH ('')
        ),1,1,'') as Location --//Do You want to add another column just you have to use another stuff stmt.
    from #temp1  t
    group by t.Name 


   DROP TABLE #temp1;

 DROP TABLE #temp2;

No comments:

Post a Comment