需要在一些工具中存盤歐洲央行的匯率,其中存盤了 MS SQL 服務器查詢,并且無法從 XML 網頁獲取資訊。
這是網路上的源 XML 與匯率 https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
這些是我的實驗:我創建 XML 變數并由 XML 填充(稍后 XML 將在表中的 nvarchar 列中)
DECLARE @RateXML XML
SELECT @RateXML = '
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2022-02-16">
<Cube currency="USD" rate="1.1372"/>
<Cube currency="JPY" rate="131.56"/>
<Cube currency="BGN" rate="1.9558"/>
</Cube>
</Cube>
</gesmes:Envelope>';
我試過這些,沒有人作業。
WITH XMLNAMESPACES ('uri' as gesmes)
select a.currency.query('Cube/@currency') as currency from @RateXML.nodes('gesmes:Envelope/Cube/Cube') as a(currency);
--Error: Attribute may not appear outside of an element
WITH XMLNAMESPACES ('uri' as gesmes)
select a.currency.value('Cube/@currency', 'varchar(max)') as currency from @RateXML.nodes('gesmes:Envelope/Cube/Cube') as a(currency);
-- 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'
WITH XMLNAMESPACES ('uri' as gesmes)
select @RateXML.query('gesmes:Envelope/Cube/Cube/Cube/@currency') as currency;
-- Attribute may not appear outside of an element
有沒有不同的簡單方法?我想選擇一個有 2 列的臨時表,即 currenty 和 rate。感謝您嘗試...
uj5u.com熱心網友回復:
以下是如何正確操作。
應該注意這兩個名稱空間。正如@RonenAriely 提到的,您需要宣告和使用命名空間。
稍后 XML 將在表中的 nvarchar 列中
最好使用 XML 資料型別的列。
好處:
- XML 資料型別存盤量遠小于
NVARCHAR(MAX) - XML 資料型別具有強大的 XQuery API 來處理對 XML 資料的任何操作。
- XML 資料型別具有特殊的 XML 索引以提高性能。3種指標。
SQL
DECLARE @RateXML XML =
'<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2022-02-16">
<Cube currency="USD" rate="1.1372"/>
<Cube currency="JPY" rate="131.56"/>
<Cube currency="BGN" rate="1.9558"/>
</Cube>
</Cube>
</gesmes:Envelope>';
;WITH XMLNAMESPACES (DEFAULT 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'
, 'http://www.gesmes.org/xml/2002-08-01' AS gesmes)
SELECT c.value('@currency', 'CHAR(3)') AS currency
, c.value('@rate', 'DECIMAL(10,4)') AS rate
FROM @RateXML.nodes('/gesmes:Envelope/Cube/Cube/Cube') AS t(c);
輸出
---------- ----------
| currency | rate |
---------- ----------
| USD | 1.1372 |
| JPY | 131.5600 |
| BGN | 1.9558 |
---------- ----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425849.html
上一篇:在where子句中匹配多個列
