Thursday, April 19, 2012

Online XML Parsing in SQL

sp_configure 'Show Advanced Option',1
Reconfigure
go
sp_configure 'Ole Automation Procedures',1
Reconfigure
go

Declare @Object as Int;

Declare @ResponseText1 as Varchar(8000);

Declare @Url as Varchar(MAX);

select @Url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'

Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;

Exec sp_OAMethod @Object, 'open', NULL, 'get', @Url, 'false'

Exec sp_OAMethod @Object, 'send'

Exec sp_OAMethod @Object, 'responseText', @ResponseText1 OUTPUT

Exec sp_OADestroy @Object --load into Xml

Declare @XmlResponse as xml;

select @XmlResponse = CAST(@ResponseText1 as xml)

;with xmlnamespaces ( 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref' as Envelope,

'http://www.gesmes.org/xml/2002-08-01' as gesmes )

select x.i.value('@rate','money') [Money],x.i.value('@currency','char(3)') As [Currency]

from @XmlResponse.nodes('/gesmes:Envelope/Envelope:Cube/Envelope:Cube/Envelope:Cube') as x(i)