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

前端之家收集整理的这篇文章主要介绍了如何使用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
原文链接:https://www.f2er.com/mssql/83888.html

猜你在找的MsSQL相关文章