从存储过程调用 Web Api 2 端点

Call a Web Api 2 endpoint from a stored procedure

一些遗留 SQL 存储过程 (SQL Server 2008) 需要从我提供的 Web 服务 (Web Api 2) 获取一些信息。

如何调用端点(在 GET 中)、检索数据(JSON 格式)和翻译 临时 table 接收到的数据在存储过程的其余部分中使用?

谢谢

最好的方法是创建 Used-defined CLR function and call your Web API from there, so you can use full power of C# and .Net libraries to do web calls and parse Json. There is plenty of information on the internet about that. For example: https://blogs.msdn.microsoft.com/spike/2010/11/25/how-to-consume-a-web-service-from-within-sql-server-using-sql-clr/。这与 WebAPI 无关,但您可以从那里得到灵感。

请注意,这需要将带有 CLR 函数的自定义程序集部署到 SQL 服务器。

编辑:

有一种方法可以在 TSQL 中使用 OLE Automation. See an example here 来实现,但它更难,文档更少,您可能会花时间发明自己的自行车而不是使用现成的解决方案来自 CLR 函数。

无需编写 CLR 即可轻松完成:

Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
                 'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Select @ResponseText

Exec sp_OADestroy @Object

尝试使用此 CLR 存储过程:SQL-APIConsumer

 exec  [dbo].[APICaller_POST]
       @URL = 'http://localhost:5000/api/auth/login'
      ,@BodyJson = '{"Username":"gdiaz","Password":"password"}'