SQL Server XML多级查询

时间:2018-12-19 13:56:57

标签: sql sql-server xml tsql sql-server-2016

我需要查询以下xml:

declare @xml xml = '<root>
    <level1>
        <property1>Value1</property1>
        <property2>Value2</property2>
        <level2List>
            <level2>Child1</level2>
            <level2>Child2</level2>
        </level2List>
    </level1>
    <level1>
        <property1>Value3</property1>
        <property2>Value4</property2>
        <level2List>
            <level2>Child3</level2>
            <level2>Child4</level2>
        </level2List>
    </level1>
</root>'

我需要以下结果:

Property1 Property2 Child
Value1    Value2    Child1
Value1    Value2    Child2
Value3    Value4    Child3
Value3    Value4    Child4

我有这个查询:

select col.value('Property1','varchar(100)') Property1,
       col.value('Property2','varchar(100)') Property2
from @xml.nodes('//root/level1') as tab(col)

但是我不知道如何将父节点与其子节点合并。有想法吗?

3 个答案:

答案 0 :(得分:2)

我将使用以下内容:

SELECT
    X.value('(../../property1)[1]', 'varchar(20)') Property1,
    X.value('(../../property2)[1]', 'varchar(20)') Property2,
    X.value('.', 'varchar(20)') Child
FROM @xml.nodes('//level2') N(X)

答案 1 :(得分:2)

您可以从底部开始搜索:

DECLARE @xml AS XML = '<root>
    <level1>
        <property1>Value1</property1>
        <property2>Value2</property2>
        <level2List>
            <level2>Child1</level2>
            <level2>Child2</level2>
        </level2List>
    </level1>
    <level1>
        <property1>Value3</property1>
        <property2>Value4</property2>
        <level2List>
            <level2>Child3</level2>
            <level2>Child4</level2>
        </level2List>
    </level1>
</root>';

SELECT
    n.value('../../property1[1]','varchar(100)') property1,
    n.value('../../property2[1]','varchar(100)') property2,
    n.value('.','varchar(100)') Child
FROM @xml.nodes('//level1//level2') AS x(n)

或通过扩展您的原始尝试:

FROM @xml.nodes('//level1') AS n1(l1)
CROSS APPLY l1.nodes('.//level2') AS n2(l2)

答案 2 :(得分:1)

您也可以使用APPLY

SELECT col.value('property1[1]', 'varchar(100)') AS property1,
       col.value('property2[1]', 'varchar(100)') AS property2,
       col1.value('text()[1]','varchar(100)') AS Child
FROM @xml.nodes('root/level1') AS tab(col) OUTER APPLY 
     col.nodes('level2List/level2') tab1(col1);