SQL Help: Select statement Concatenate a One to Many relationship

后端 未结 8 1731
天涯浪人
天涯浪人 2021-01-03 16:28

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

8条回答
  •  情话喂你
    2021-01-03 17:12

    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
    

提交回复
热议问题