I want to write an SQL Server query that will retrieve data from the following example tables:
Table: Person
ID Name
-- ----
1 Bill
2 B
What you are looking for is something like SQL Server's FOR XML PATH('') which combines results as a rowset
Select Person.Name,
(
Select SkillName + ','
From SkillLink
inner join skill on skill.id = skilllink.skillid
Where SkillLink.PersonID = Person.ID FOR XML PATH('')
)
as Skills
FROM Person
You would use FOR XML PATH
for this:
select p.name,
Stuff((SELECT ', ' + s.skillName
FROM skilllink l
left join skill s
on l.skillid = s.id
where p.id = l.personid
FOR XML PATH('')),1,1,'') Skills
from person p
See SQL Fiddle with Demo
Result:
| NAME | SKILLS |
----------------------------
| Bill | Telepathy, Karate |
| Bob | (null) |
| Jim | Carpentry |
What you are looking for is something like SQL Server's FOR XML PATH which combines results as a rowset