TSQL - XML查询帮助

时间:2011-01-31 06:57:07

标签: sql-server xml tsql xpath

我有这种格式的XML

<tests>
    <test>
        <testid>1</testid>
        <testval>8</testval>
        <testname>
            <testid>1</testid>
            <testname>test 1</testname>
        </testname>
    </test>
    <test>
        <testid>2</testid>
        <testval>5</testval>
        <testname>
            <testid>2</testid>
            <testname>test 2</testname>
        </testname>
    </test>
</tests>

使用TSQL / XML查询如何实现此结果

[Testid][TestVal][TestName]
    1       8      Test 1
    2       5      Test 2

1 个答案:

答案 0 :(得分:5)

试试这个:

declare @input XML = '<tests>
    <test>
        <testid>1</testid>
        <testval>8</testval>
        <testname>
            <testid>1</testid>
            <testname>test 1</testname>
        </testname>
    </test>
    <test>
        <testid>2</testid>
        <testval>5</testval>
        <testname>
            <testid>2</testid>
            <testname>test 2</testname>
        </testname>
    </test>
</tests>'

select
    Tests.value('(testid)[1]', 'int') as 'TestID',
    Tests.value('(testval)[1]', 'int') as 'TestVal',
    Tests.value('(testname/testname)[1]', 'varchar(20)') as 'TestName'
FROM 
    @input.nodes('/tests/test') as List(Tests)

这为您提供了所需的输出。

如果您有这些XML列的表,则可能需要使用稍微不同的方法(使用CROSS APPLY):

select
    tbl.SomeValue, tbl.SomeOtherValue,
    Tests.value('(testid)[1]', 'int') as 'TestID',
    Tests.value('(testval)[1]', 'int') as 'TestVal',
    Tests.value('(testname/testname)[1]', 'varchar(20)') as 'TestName'
FROM 
    dbo.YourTable tbl
CROSS APPLY
    tbl.XmlColumn.nodes('/tests/test') as List(Tests)