Can you call a webservice from TSQL code?

前端 未结 9 1799
野趣味
野趣味 2020-11-29 00:39

Is there a way to call out from a TSQL stored procedure or function to a webservice?

9条回答
  •  自闭症患者
    2020-11-29 01:02

    Here'a an example to get some data from a webservice. In this case parse a user agent string to JSON.

    --first configure MSSQL to enable calling out to a webservice (1=true, 0=false)
    sp_configure 'show advanced options', 1;  
    GO  
    RECONFIGURE;  
    GO  
    sp_configure 'Ole Automation Procedures', 1;  
    GO  
    RECONFIGURE;  
    GO  
    
    CREATE PROCEDURE CallWebAPI_ParseUserAgent @UserAgent VARCHAR(512)
    AS
    BEGIN
        SET NOCOUNT ON;
    
        DECLARE @Object INT;
        DECLARE @ResponseText AS VARCHAR(8000);
        DECLARE @url VARCHAR(512)
    
        SET @url = 'http://www.useragentstring.com/?getJSON=all&uas=' + @UserAgent;
    
        EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @Object OUT;
        EXEC sp_OAMethod @Object, 'Open', NULL, 'GET', @url, 'false'
        EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
        EXEC sp_OAMethod @Object, 'send'
        EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
        SELECT @ResponseText
        EXEC sp_OADestroy @Object
    END
    
    --example how to call the API
    CallWebAPI_ParseUserAgent 'Mozilla/5.0 (Windows NT 6.2; rv:53.0) Gecko/20100101 Firefox/53.0'
    

提交回复
热议问题