T-SQL将xml字段转换为多列表

时间:2016-06-27 08:25:22

标签: sql xml

我正在尝试将数据从xml字段转换为表格。我在这个网站上找到了多个解决方案,但它们似乎都没有给我我所需要的。 xml看起来像这样:

    <table>
  <id>{100}</id>
  <rows>
    <row>
      <columns>
        <column name="cur" value="EUR" type="System.String" />
        <column name="item" value="Item a" type="System.String" />
        <column name="price" value="2.5" type="System.Decimal" />
        <column name="qty" value="20" type="System.Int32" />
        <column name="Key" value="1" type="System.Int32" />
      </columns>
    </row>
    <row>
      <columns>
        <column name="cur" value="EUR" type="System.String" />
        <column name="item" value="Item b" type="System.String" />
        <column name="price" value="30" type="System.Decimal" />
        <column name="qty" value="30" type="System.Int32" />
        <column name="Key" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>Key</key>
</table>

我希望结果如下:

id  key cur  item    price  qty
100 1   EUR  Item a  2.5    20
100 2   EUR  Item b  30     30

我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

试试这样:

DECLARE @x XML=
'<table>
  <id>{100}</id>
  <rows>
    <row>
      <columns>
        <column name="cur" value="EUR" type="System.String" />
        <column name="item" value="Item a" type="System.String" />
        <column name="price" value="2.5" type="System.Decimal" />
        <column name="qty" value="20" type="System.Int32" />
        <column name="Key" value="1" type="System.Int32" />
      </columns>
    </row>
    <row>
      <columns>
        <column name="cur" value="EUR" type="System.String" />
        <column name="item" value="Item b" type="System.String" />
        <column name="price" value="30" type="System.Decimal" />
        <column name="qty" value="30" type="System.Int32" />
        <column name="Key" value="2" type="System.Int32" />
      </columns>
    </row>
  </rows>
  <key>Key</key>
</table>';
SELECT @x.value('(/table/id)[1]','varchar(max)') AS id --are the curly brackets there on purpose?
      ,Rw.value('(columns/column[@name="Key"]/@value)[1]','int') AS [key] 
      ,Rw.value('(columns/column[@name="cur"]/@value)[1]','varchar(max)') AS cur 
      ,Rw.value('(columns/column[@name="item"]/@value)[1]','varchar(max)') AS item 
      ,Rw.value('(columns/column[@name="price"]/@value)[1]','decimal(10,4)') AS price 
      ,Rw.value('(columns/column[@name="qty"]/@value)[1]','int') AS qty 
 FROM @x.nodes('/table/rows/row') AS A(Rw)