1
<University>
  <RegistrationCode>12859</RegistrationCode>
  <Colleges>
    <College>
      <CollegeCode>0001</CollegeCode>
      <CollegeName>NIMS</CollegeName>
    </College>
    <College>
      <CollegeCode>0002</CollegeCode>
      <CollegeName>OXFORD</CollegeName>
    </College>
  </Colleges>
</University>

我想使用 SQL Query 从上面的 XML 中提取下面的内容。有人可以帮我吗?

RegistrationCode   CollegeCode      CollegeName
-----------------------------------------------
12859              0001             NIMS
12859              0002             OXFORD
4

1 回答 1

1

尝试这个:

DECLARE @input XML = '<University>
<RegistrationCode>12859</RegistrationCode>
<Colleges>
<College>
<CollegeCode>0001</CollegeCode>
<CollegeName>NIMS</CollegeName>
</College>
<College>
<CollegeCode>0002</CollegeCode>
<CollegeName>OXFORD</CollegeName>
</College>
</Colleges>
</University>'

SELECT
    RegistrationCode = Univ.value('(RegistrationCode)[1]', 'int'),
    CollegeCode = Colleges.value('(CollegeCode)[1]', 'int'),
    CollegeName = Colleges.value('(CollegeName)[1]', 'varchar(100)')
FROM 
    @input.nodes('University') AS XTbl(Univ)
CROSS APPLY
    Univ.nodes('Colleges/College') AS XTbl2(Colleges)

这给了我你想要的输出。

基本上,您首先需要有一个<University>节点列表(这里只有一个)来获取注册码,然后从该<University>节点中获取<Colleges>/<College>子节点,然后从CROSS APPLY这些子节点中获取大学代码和名称

于 2013-05-31T15:27:54.687 回答