1:使用 Ole Automation Procedures 选项可指定是否可以在 Transact-SQL 批处理中实例化 OLE Automation 对象。还可以使用基于策略的管理或者 sp_configure 存储过程来配置这一选项
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2:创建HTTP请求过程
CREATE PROCEDURE [dbo].[SP_Message_GET_HttpRequestData](
@URL NVARCHAR(1000),
@status INT=0 OUT,
@returnText NVARCHAR(1000)='' OUT
)
AS
BEGIN
DECLARE @object INT,
@errSrc INT
/*初始化对*/
EXEC @status = SP_OACreate 'Msxml2.ServerXMLHTTP.3.0', @object OUT
IF @status <> 0
BEGIN
EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
RETURN
END
/*创建链接*/
EXEC @status= SP_OAMethod @object,'open',NULL,'GET',@URL
IF @status <> 0
BEGIN
EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
RETURN
END
EXEC @status=SP_OAMethod @object,'setRequestHeader','Content-Type','application/x-www-form-urlencoded'
/*发起请求*/
EXEC @status= SP_OAMethod @object,'send',NULL
IF @status <> 0
BEGIN
EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
RETURN
END
/*获取返回*/
EXEC @status= SP_OAGetProperty @object,N'responseText',@returnText OUT
IF @status <> 0
BEGIN
EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
RETURN
END
END;
3:HTTP 请求返回值
CREATE PROCEDURE [dbo].[SP_Message_IPCC_WEBSERVICE_PACKID](@parametersStr NVARCHAR(1000),@outText NVARCHAR (1000) OUT)
AS
BEGIN
DECLARE @returnText NVARCHAR(1000)
DECLARE @status INT
DECLARE @urlStr NVARCHAR(1000)
SET @urlStr = @parametersStr
EXEC SP_Message_GET_HttpRequestData @urlStr, @status OUTPUT, @returnText OUTPUT;
SET @outText = LEFT(@returnText,1000);
PRINT @outText ; ---打印
END;
4:T/SQL 获取JSON 中指定的值
CREATE FUNCTION [dbo].[Fn_FindJson]
(
@code NVARCHAR(100),
@json NVARCHAR(2000))
RETURNS NVARCHAR(500)
AS
BEGIN
DECLARE @codeindex AS INT
DECLARE @valueindex AS INT
DECLARE @endindex AS INT
SET @codeindex = CHARINDEX(@code,@json)
--没有找到code项
IF (@codeindex = 0) RETURN ''
SET @valueindex = CHARINDEX(':',@json,@codeindex)
SET @endindex = CHARINDEX(',',@json,@codeindex)
IF (@endindex = 0) SET @endindex = CHARINDEX('}',@json,@codeindex)
--格式不对 return ''
IF (@valueindex = 0 OR @endindex = 0) RETURN ''
--正常返回
RETURN REPLACE(SUBSTRING(@json,@valueindex+1,@endindex-@valueindex-1),'''','')
END
5:测试
DECLARE @mobile_phone CHAR(11)=18566209581
DECLARE @outText NVARCHAR(1000),@json NVARCHAR(1000),@url NVARCHAR(1000)
SET @url='http://virtual.paipai.com/extinfo/GetMobileProductInfo?mobile='+@mobile_phone+'&amount=10000&callname=getPhoneNumInfoExtCallback'
EXEC SP_Message_IPCC_WEBSERVICE_PACKID @url,@outText OUTPUT
SET @json=SUBSTRING(@outText,CHARINDEX('{',@outText),Charindex('}',@outText)-CHARINDEX('{',@outText)+1)
SELECT dbo.Fn_FindJson('mobile',@json)mobile_phone,dbo.Fn_FindJson('province',@json)province,dbo.Fn_FindJson('isp',@json)isp,dbo.Fn_FindJson('cityname',@json)city,''area_code