如何使用SQL Server从URL读取XML

时间:2017-11-02 06:28:25

标签: sql sql-server-2008 sql-server-2005 sql-server-2012 sql-server-2008-r2

我创建了以下函数来从XML检索数据。我想从生成的XML中获取formatted_address。如何获得所需的结果?我得到了NULL值。我想只使用函数

获得所需的结果
CREATE FUNCTION [dbo].[GetLocation]
     (@latt VARCHAR(150), @lont VARCHAR(150)) 
RETURNS varchar(max) 
AS 
BEGIN 
    DECLARE @output NVARCHAR(MAX)
    DECLARE @URL VARCHAR(8000) 
    DECLARE @Response NVARCHAR(1024)
    DECLARE @XML XML
    DECLARE @Obj INT 
    DECLARE @Result INT
    DECLARE @HTTPStatus INT
    DECLARE @ErrorMsg VARCHAR(MAX)
    DECLARE @ConvertVar VARCHAR(8000)
    DECLARE @lat VARCHAR(150) 
    DECLARE @lon VARCHAR(150)

    SET @lat = @latt
    SET @lon = @lont

    SET @URL ='https://maps.googleapis.com/maps/api/geocode/xml?latlng=23.56320001,46.66140002'

    EXEC sp_OACreate 'MSXML2.XMLHttp', @obj OUT
    EXEC sp_OAMethod @obj, 'open', NULL, 'GET', @URL, false
    EXEC sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
    EXEC sp_OAMethod @Obj, send, NULL, ''
    EXEC sp_OAGetProperty @obj, 'ResponseText', @Response OUTPUT

    SET @Response = replace(@Response, '<?xml version="1.0" encoding="UTF-8" ?>', '')    
    SET @XML = convert(xml,@Response)
    SET @output = (SELECT   
                       T.c.value('formatted_address[1]','nvarchar(500)')                    
                   FROM   
                       @XML.nodes('reversegeocode/result[1]') T(c))

    RETURN @output
END

0 个答案:

没有答案