Here is a my SQL:
create table sqm (data xml)
insert into sqm
select '<DataSet xmlns="http://www.bnr.ro/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd">
<Cube date="2017-06-30">
<Rate currency="AED">1.0867</Rate>
<Rate currency="AUD">3.0665</Rate>
<Rate currency="BGN">2.3284</Rate>
</Cube>
</DataSet>'
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/DataSet/Body/Cube') as m(c)
After spending hours trying to find out why my SQL kept returning NULL in the db, I discovered that my problem was due to Hyperlink references at the very beginning of the XML(after DataSet). I really want to know why is this happening and who can I delete everything between <DataSet
end >
. Is there any other option?
if you can think of a better title, please edit.
You need to declare the namespace using WITH XMLNAMESPACES
Also your example XML has no Body
element so I removed that from the Xpath.
WITH XMLNAMESPACES (DEFAULT 'http://www.bnr.ro/xsd')
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/DataSet/Cube') as m(c)
Or alternatively you can use
select
m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('/*:DataSet/*:Cube') as m(c)
Apart of Martin's solutions(+1), there is one more solution that is using inline declaration of XML namespaces thus:
-- Solution #1
select m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('declare default element namespace "http://www.bnr.ro/xsd";DataSet/Cube') as m(c)
-- Solution #2
select m.c.value('@date', 'date') as valuta
from sqm as s
outer apply s.data.nodes('
declare default element namespace "http://www.bnr.ro/xsd";
declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance";
declare namespace schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd";
DataSet/Cube') as m(c)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.