开发者

TSQL - XML query help

I have an XML in this format

<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&g开发者_开发问答t;
</tests>

using TSQL/XML query how do I achieve this result

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


Try this:

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)

This gives you the desired output.

If you have a table of those XML columns, you might need to use a slightly different approach (using 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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜