微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用T-SQL从URL读取XML?

在url中有xml文件
<response>
<sum>0</sum>
<result>0</result>
<comment>sel*1.9488|buy*1.9453</comment>
</response>

现在想要存储过程,我可以从url解析这个xml文件,并更新为< comment>中的列值.ll * 1.9488 | buy * 1.9453< / comment>想添加购买* 1.9453到我的桌子.怎么样?

解决方法

要从URL获取XML,您需要执行以下操作:

启用Ole Automation Procedures

sp_configure 'show advanced options',1;
GO
RECONfigURE;
GO
sp_configure 'Ole Automation Procedures',1;
GO
RECONfigURE;
GO

然后,为了从URL获取XML(基于here的更新版本回答),下面创建一个临时表来存储该值,以便您可以使用xpath和子字符串处理结果.

这是一个使用google maps xml的工作示例,您需要更新url和xpath以满足您的特定要求.

USE tempdb
GO

IF OBJECT_ID('tempdb..#xml') IS NOT NULL DROP TABLE #xml
CREATE TABLE #xml ( yourXML XML )
GO

DECLARE @URL VARCHAR(8000) 

DECLARE @QS varchar(50)

-- & or ? depending if there are other query strings
-- Use this for when there is other query strings:
SELECT @QS = '&date='+convert(varchar(25),getdate(),126)
-- Use this for when there is NO other query strings:
-- SELECT @QS = '?date='+convert(varchar(25),126)
SELECT @URL = 'http://maps.google.com/maps/api/geocode/xml?latlng=10.247087,-65.598409&sensor=false'  + @QS

DECLARE @Response varchar(8000)
DECLARE @XML xml
DECLARE @Obj int 
DECLARE @Result int 
DECLARE @HTTPStatus int 
DECLARE @ErrorMsg varchar(MAX)

EXEC @Result = sp_OACreate 'MSXML2.XMLHttp',@Obj OUT 

EXEC @Result = sp_OAMethod @Obj,'open',NULL,'GET',@URL,false
EXEC @Result = sp_OAMethod @Obj,'setRequestHeader','Content-Type','application/x-www-form-urlencoded'
EXEC @Result = sp_OAMethod @Obj,send,''
EXEC @Result = sp_OAGetProperty @Obj,'status',@HTTPStatus OUT 

INSERT #xml ( yourXML )
EXEC @Result = sp_OAGetProperty @Obj,'responseXML.xml'--,@Response OUT 

SELECT  yourXML.value('(//GeocodeResponse/status)[1]','VARCHAR(MAX)') from #xml

为了插入子字符串,您需要执行类似这样的操作以返回管道后的所有内容添加到表中:

INSERT tableDestination (valueDestination)
SELECT  substring(yourXML.value('(//response/comment)[1]','VARCHAR(MAX)'),charindex('|',yourXML.value('(//response/comment)[1]',1)+1,len(yourXML.value('(//response/comment)','VARCHAR(MAX)'))) from #xml

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐