For example I have two tables. The first table is student while the second table are the courses that the a student is taking. How can I use a select statement so that I can
So you want to see:
'Jade', 'Math, English, History'
'Kieveli', 'History, Biology, Physics'
Yes, comma separated is always desirable, but SQL isn't good at it. Here's the approach I was always planning on using:
Create a Function on the SQL server that uses a cursor to loop over the subquery (sorry - I didn't fully test this):
CREATE FUNCTION commacourselist(@studentname varchar(100))
RETURNS @List varchar(4096)
AS
BEGIN
DECLARE @coursename varchar(100)
DECLARE FOR
SELECT course.name FROM course WHERE course.studentname = @studentname
OPEN coursecursor
FETCH NEXT FROM coursecursor INTO @coursename
WHILE @@FETCH_STATUS = 0
BEGIN
IF @List = ''
BEGIN
SET @List = @coursename
END
ELSE
BEGIN
SET @List = @List + ',' + @coursename
END
FETCH NEXT FROM coursecursor INTO @coursename
END
CLOSE coursecursor
DEALLOCATE coursecursor
RETURN
END
GO
Then call the function in the query:
SELECT student.name,
commacourselist( student.name )
FROM student