Sql-Server

從 xml 片段中提取數據

  • April 17, 2017

在 SQL Server 2014 中,我有以下 xml 片段:

<salesorder>
  <ordnum>123</ordnum>
  <orddate>2017-04-17</orddate>
  <details>
     <detail>
        <itemtype>Stationery</itemtype>
        <itemdesc>Pencil</itemdesc>
        <specifications>
           <specification>
              <name>Qty</name>
              <value>5</value>
           </specification>
           <specification>
              <name>Description</name>
              <value>Pencil H1</value>
           </specification>
           <specification>
              <name>Price</name>
              <value>1.50</value>
           </specification>
        </specifications>
     </detail>
     <detail>
        <itemtype>Stationery</itemtype>
        <itemdesc>Pencil</itemdesc>
        <specifications>
           <specification>
              <name>Qty</name>
              <value>10</value>
           </specification>
           <specification>
              <name>Description</name>
              <value>Pencil H2</value>
           </specification>
           <specification>
              <name>Colour</name>
              <value>Red</value>
           </specification>
           <specification>
              <name>Price</name>
              <value>2.75</value>
           </specification>
        </specifications>
     </detail>
  </details>
</salesorder>

我想提取以下數據:

ordnum   itemtype     qty   price
123      Stationery   5     1.50
123      Stationery   10    2.75

這可以在 T-SQL 中完成嗎?

在此先感謝,議員

在變數中使用您的 XML @X

select @X.value('(salesorder/ordnum/text())[1]', 'int') as ordnum,
      T.X.value('(itemtype/text())[1]', 'varchar(15)') as itemtype,
      T.X.value('(specifications/specification[name/text() = "Qty"]/value/text())[1]', 'int') as qty,
      T.X.value('(specifications/specification[name/text() = "Price"]/value/text())[1]', 'money') as price
from @X.nodes('/salesorder/details/detail') as T(X);

該查詢中最複雜的部分可能是用於獲取 和 值的 XQueryQty表達式Price

[name/text() = "Qty"]是一個謂詞,它查看節點的值,name如果是則返回 true Qty

其餘的是基本的 XML 查詢內容,使用nodes()將 XML 切碎/salesorder/details/detail以獲取每個詳細元素的一行,並使用value()從 XML 中提取所需的值。

引用自:https://dba.stackexchange.com/questions/171160