开发者

How do I generate nested XML for many to many relationship in sql server 2008?

The situation is there are courses and lecturers and they have a many to many relationship (1 course can have many lecturers, 1 lecturer can teach many courses)

The following XML repeats the course name:

SELECT
    C.COURSE_ID "@course_id"
    ,   C.COURSE_NAME "Course_Name"
    --get lecturer id(s) of the course
    ,   CL.LECTURER_ID  

    FROM 
    COURSE C LEFT JOIN COURSE_LECTURER CL ON C.COURSE_ID = CL.COURSE_ID
    --LEFT JOIN AS ALL COURSES DON'T HAVE LECTURERS COULD BE INNER :)
FOR XML PATH('Course'), ROOT('Program')

It gives me the following output (snippet):

<Course course_id="ISFND 1.1">
    <Course_Name>Relational Databases and SQL</Course_Name>
    <LECTURER_ID>ME123</LECTURER_ID>
  </Course>
  <Course course_id="ISFND 1.1">
    <Course_Name>Relational Databases and SQL</Course_Name>
    <LECTURER_ID>HS123</LECTURER_ID>
  </Course>

But the output I want is:

<Course course_id="ISFND 1.1">
    开发者_JAVA百科    <Course_Name>Relational Databases and SQL</Course_Name>
        <LECTURER_ID>ME123</LECTURER_ID>
        <LECTURER_ID>HS123</LECTURER_ID>
      </Course>

I guess there is some problem in my sql for many to many may be I need to use IN or something like for each. Any help will be appreciated. Thank you.


SELECT
    C.COURSE_ID "@course_id"
    ,   C.COURSE_NAME "Course_Name"
    , (SELECT CL.LECTURER_ID
       FROM COURSE_LECTURER CL
       WHERE C.COURSE_ID = CL.COURSE_ID
       FOR XML PATH(''), TYPE)
FROM COURSE C
FOR XML PATH('Course'), ROOT('Program')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜