从sql server表中读取XML数据

时间:2017-06-19 12:12:50

标签: sql-server

我有以下带有此数据的XML列:

<Motion>
     <LimitationTypes>
        <LimitationTypeId>6</LimitationTypeId>
        <LimitationTypeId>5</LimitationTypeId>
        <LimitationTypeId>4</LimitationTypeId>
        <LimitationTypeId>3</LimitationTypeId>
    </LimitationTypes>
</Motion>

如何将输出作为包含4行的表格?

1 个答案:

答案 0 :(得分:0)

您可以使用以下脚本:

DECLARE @MyXML XML
SET @MyXML = '<Motion>
                 <LimitationTypes>
                    <LimitationTypeId>6</LimitationTypeId>
                    <LimitationTypeId>5</LimitationTypeId>
                    <LimitationTypeId>4</LimitationTypeId>
                    <LimitationTypeId>3</LimitationTypeId>
                </LimitationTypes>
            </Motion>'

SELECT
    a.b.value('LimitationTypes[1]/LimitationTypeId[1]','varchar(10)') AS LimitationTypeId1,
    a.b.value('LimitationTypes[1]/LimitationTypeId[2]','varchar(10)') AS LimitationTypeId2,
    a.b.value('LimitationTypes[1]/LimitationTypeId[3]','varchar(10)') AS LimitationTypeId3,
    a.b.value('LimitationTypes[1]/LimitationTypeId[4]','varchar(10)') AS LimitationTypeId4
FROM @MyXML.nodes('Motion') a(b)

获得以下结果:

enter image description here

以下内容也适用,您只需编写LimitationTypes一次:

SELECT
    a.b.value('LimitationTypeId[1]','varchar(10)') AS LimitationTypeId1,
    a.b.value('LimitationTypeId[2]','varchar(10)') AS LimitationTypeId2,
    a.b.value('LimitationTypeId[3]','varchar(10)') AS LimitationTypeId3,
    a.b.value('LimitationTypeId[4]','varchar(10)') AS LimitationTypeId4
FROM @MyXML.nodes('Motion/LimitationTypes') a(b)

您可以在nodes() Method (xml Data Type) 上详细了解nodes()方法。

  

编辑:

对于行,可以这样做:

SELECT
    'LimitationTypeId1' as col, a.b.value('LimitationTypeId[1]','varchar(10)') AS val
FROM @MyXML.nodes('Motion/LimitationTypes') a(b)
UNION ALL
SELECT
    'LimitationTypeId2' as col, a.b.value('LimitationTypeId[2]','varchar(10)') AS val
FROM @MyXML.nodes('Motion/LimitationTypes') a(b)
UNION ALL
SELECT
    'LimitationTypeId3' as col, a.b.value('LimitationTypeId[3]','varchar(10)') AS val
FROM @MyXML.nodes('Motion/LimitationTypes') a(b)
UNION ALL
SELECT
    'LimitationTypeId4' as col, a.b.value('LimitationTypeId[4]','varchar(10)') AS val
FROM @MyXML.nodes('Motion/LimitationTypes') a(b)