Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Friday, November 28, 2014

Concatinating values and return as single value column in MS SQL Server

For 1 to many relationship between 2 tables, you may want to return this result:

Person Name Gadgets
Amy LG, Samsung, Sony
Bea Blackberry, iPhone

select p.name as "Person Name", STUFF((                                         
 SELECT ',' gadget_name
 FROM gadget g              
 WHERE p.person_id = g.person_id               
 FOR XML PATH('')), 1, 1, '') as "Gadgets"
from person

Concatenation is done by the FOR XML PATH; whereas the STUFF is to simply remove the first comma (",").