You can use FOR XML PATH('')
in an inner query to get the concatenated values and then use it to match with CourseEventKey
from the outer query:
;WITH CTE
AS
(
SELECT DISTINCT
ces.CourseEventKey,
up.Firstname + ' ' + up.Lastname AS Name
FROM InstructorCourseEventSchedule ices
INNER JOIN CourseEventSchedule ces ON ces.CourseEventScheduleKey = ices.MemberKey
INNER JOIN UserProfile up ON up.UserKey = ices.UserKey
WHERE ces.CourseEventKey IN
(
SELECT CourseEventKey
FROM @CourseEvents
)
)
SELECT DISTINCT i1.CourseEventKey,
STUFF(
(SELECT
'; ' + Name
FROM CTE i2
WHERE i1.CourseEventKey = i2.CourseEventKey
FOR XML PATH(''))
,1,2, ''
)
FROM CTE i1
ORDER BY i1.CourseEventKey