I have a (temp) table which contains student records.
There is another table which contains which students enrolled for which subjects.
I would like to update the student table with subjects aggregated into it as shown below.
StudentID Name Subjects
1 Ryan
2 James
StudentID Subject
1 Maths
1 Science
2 History
StudentID Name Subjects
1 Ryan Maths, Science
2 James History
I've tried this, but it updates only with first record found. Aggregation wont happen.
declare @Subjects NVARCHAR(max) = ''
UPDATE #Students
SET Subjects = (@Subjects + CASE @Subjects WHEN '' THEN '' ELSE '; ' END + ISNULL(StudentSubjects.Subject,' '))
FROM #Students
INNER JOIN StudentSubjects ON #Students.StudentID = StudentSubjects.StudentID
SQL Server 2008 R2.
EDIT:
I am updating the temp table inside a stored procedure which will be rendered out in a resultset. Not updating the actual data.