我有一个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)
答案 0 :(得分: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)