我正在尝试从XML字段查询数据,这对我来说是新事物。尽管进行了大量搜索,但我找不到适合我的数据的良好示例。所以...
该表具有字段ReceiptId(PKey)和XMLData XMLData字段看起来像这样……
<?xml version="1.0" encoding="utf-8"?>
<receipt number="1" datetime="Wed May 15 08:08:39 PDT 2019" total="75.00">
<items>
<item productid="MULTI" quantity="1" amount="184.00" />
<fees>
<f feeid="Fee1" calculated="5.00" reason="" />
<f feeid="Fee2" calculated="10.00" reason="" />
<f feeid="Fee3" calculated="15.00" reason="" />
<f feeid="Fee4" calculated="20.00" reason="" />
<f feeid="Fee5" calculated="25.00" reason="" />
</fees>
</items>
</receipt>
现在开始提问... 我的SQL Select将如何计算得出Fee3的计算金额(例如15.00)?有时候Fee3不在XMLData中,所以我需要某种Exists()语句。
感谢您帮助编写一个完整的新书。
答案 0 :(得分:0)
假设您的值存储为xml
,则可以执行以下操作:
DECLARE @XML xml = '<?xml version="1.0" encoding="utf-8"?>
<receipt number="1" datetime="Wed May 15 08:08:39 PDT 2019" total="75.00">
<items>
<item productid="MULTI" quantity="1" amount="184.00" />
<fees>
<f feeid="Fee1" calculated="5.00" reason="" />
<f feeid="Fee2" calculated="10.00" reason="" />
<f feeid="Fee3" calculated="15.00" reason="" />
<f feeid="Fee4" calculated="20.00" reason="" />
<f feeid="Fee5" calculated="25.00" reason="" />
</fees>
</items>
</receipt>';
SELECT f.value('@calculated','varchar(5)') AS calculated
FROM (VALUES(@XML))V(X)
CROSS APPLY V.X.nodes('receipt/items/fees/f') X(f)
WHERE f.value('@feeid','varchar(5)') = 'Fee3';
您使用nodes
将数据每个f
分成1行,然后使用value
获得value
。