在SQL Server中解析多级XML

时间:2015-09-18 10:48:32

标签: sql-server xml

我需要使用多级多元素解析XML。

示例XML:

<Studies>
    <Study ID="1">
        <Site Id="1">
            <Participant ID="111"/>
            <Participant ID="222"/>
        </Site>
        <Site Id="2">
            <Participant ID="333"/>
            <Participant ID="444"/>
        </Site>
    </Study>
    <Study ID="2">
        <Site Id="3">
            <Participant ID="555"/>
            <Participant ID="666"/>
        </Site>
        <Site Id="4">
            <Participant ID="777"/>
            <Participant ID="888"/>
        </Site>
    </Study>
</Studies>

我试过了:

SELECT
    StudyID = XC.value('@ID', 'int'),
    SiteId = XC2.value('@Id', 'int'),
    ParticipantId =  XC3.value('@ID', 'int')
FROM 
    @Xml.nodes('//Study') AS XT(XC)
CROSS APPLY
    xc.nodes('Site') AS XT2(XC2)
CROSS APPLY
    xc.nodes('Participant') AS XT3(XC3)

这不返回任何数据。如果我改变

xc.nodes('Participant') AS XT3(XC3)

xc.nodes('//Participant') AS XT3(XC3)

它返回32行。

我期待8行。有什么指针吗?

2 个答案:

答案 0 :(得分:2)

SELECT
    StudyID = XC.value('../../@ID', 'int'),
    SiteId = XC.value('../@Id', 'int'),
    ParticipantId =  XC.value('@ID', 'int')
FROM 
    @Xml.nodes('//Studies/Study/Site/Participant') AS XT(XC)

答案 1 :(得分:1)

请尝试关注SQL XML query。您还可以参考示例教程

declare @xml xml = '
<Studies>
    <Study ID="1">
        <Site Id="1">
            <Participant ID="111"/>
            <Participant ID="222"/>
        </Site>
        <Site Id="2">
            <Participant ID="333"/>
            <Participant ID="444"/>
        </Site>
    </Study>
    <Study ID="2">
        <Site Id="3">
            <Participant ID="555"/>
            <Participant ID="666"/>
        </Site>
        <Site Id="4">
            <Participant ID="777"/>
            <Participant ID="888"/>
        </Site>
    </Study>
</Studies>'


select
    Study.value('@ID','int') as Study,
    Site.value('@Id','int') as Site,
    Participant.value('@ID','int') as Participant
from 
    @xml.nodes('/Studies/Study') as StudiesTbl(Study)
cross apply 
    StudiesTbl.Study.nodes('Site') as StudyTbl(Site) 
cross apply 
    StudyTbl.Site.nodes('Participant') as SiteTbl(Participant)