1

我有一个如下所示的 XML 数据文件:

<Sales>
    <Store Number="8" Date="2012-08-20T03:00:00">
        <Value Field="CanceledOrders" Value="65.00"/>
        <Value Field="TotalDollars" Value="13.57"/>
    </Store>
    <Store Number="10" Date="2012-08-20T03:00:00">
        <Value Field="CanceledOrders" Value="38.00"/>
        <Value Field="TotalDollars" Value="29.22"/>
    </Store>
</Sales>

我正在摸索如何将其提取到一个普通的 SQL 表中,如下所示:

+--------+---------------------+----------------+--------------+
| Number |        Date         | CanceledOrders | TotalDollars |
+--------+---------------------+----------------+--------------+
|      8 | 2012-08-20T03:00:00 | 65.00          | 13.57        |
|     10 | 2012-08-20T03:00:00 | 38.00          | 29.22        |
+--------+---------------------+----------------+--------------+

这是我到目前为止所拥有的。我不知道如何匹配 XML 属性内容值。我想匹配 /Sales/Store/Value/@Field 内容并从 /Sales/Store/Value/@Value 返回值。

DECLARE @X AS xml

SET @X = '<Sales>
  <Store Number="8" Date="2012-08-20T03:00:00">
    <Value Field="CanceledOrders" Value="65.00" />
    <Value Field="TotalDollars" Value="13.57" />
  </Store>
  <Store Number="10" Date="2012-08-20T03:00:00">
    <Value Field="CanceledOrders" Value="38.00" />
    <Value Field="TotalDollars" Value="29.22" />
  </Store>
</Sales>'

-- This is my start but it obviously doesn't return what I need.
SELECT Y.ID.value('(@Number)[1]', 'int') AS Number,
       Y.ID.value('(@Date)[1]', 'datetime') AS [Date],
       Y.ID.value('(Value/@Field)[1]', 'varchar(max)') AS "Field",
       Y.ID.value('(Value/@Value)[1]', 'varchar(max)') AS "Value"
FROM   @X.nodes('/Sales/Store') AS Y(ID) 
4

1 回答 1

1

试试这个:

SELECT 
   Y.ID.value('(@Number)[1]', 'int') AS Number,
   Y.ID.value('(@Date)[1]', 'datetime') AS [Date],
   CancelledOrders = Y.ID.value('(Value[@Field="CanceledOrders"]/@Value)[1]', 'decimal(18,4)'),
   TotalDollars = Y.ID.value('(Value[@Field="TotalDollars"]/@Value)[1]', 'decimal(18,4)')
FROM   
   @input.nodes('/Sales/Store') AS Y(ID) 
于 2012-08-28T19:49:39.727 回答