SQL调用API获取值

本文介绍如何在SQL中调用API获取JSON数据,并利用parseJSON进行解析。当传入多个日期参数时,返回的JSON串可以通过T-SQL进行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL调用API获取值

--一、首先要开启组件的配置
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ole Automation Procedures';
GO

--二、使用sqlserver调用对应的接口以及结果
--/////////////主要代码,调取API获取值/////////////////
DECLARE @ServiceUrl as varchar(1000) 
set @ServiceUrl ='http://tool.bitefu.net/jiari/'  
--////////////////////////////////////////////一共有三个API,自己查看测试后使用
--http://tool.bitefu.net/jiari/ 
--http://www.easybots.cn/holiday_api.net 
--https://www.juhe.cn/docs/api/id/177- 这个需要实名认证 
--///////////////////////////////////////////
DECLARE @data varchar(max);
set @data='d=20190430'                  
 
Declare @Object as Int
Declare @ResponseText AS  varchar(1000)   ;      
Exec sp_OACreate 'Msxml2.ServerXMLHTTP.3.0', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'POST',@ServiceUrl,'false'
Exec sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type','application/x-www-form-urlencoded'
Exec sp_OAMethod @Object, 'send', NULL, @data --发送数据
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OAGetErrorInfo @Object --异常输出

SELECT @ResponseText
--工作日为0,休息日1,节假日2。所以没有做详细判断,都取不到结果则返回-1。
Exec sp_OADestroy @Object

如果传入多个日期的话,会返回一个json串这时我们可以用parseJSON来进行解析

 DECLARE @sad NVARCHAR(200)
EXEC T_Api_Calendar '20190501,20190502,20190503',@sad OUTPUT
PRINT @sad

Select * from parseJSON(@sad) 

下面是parseJSON的创建

CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
	RETURNS @hierarchy TABLE
	  (
	   element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
	   sequenceNo [int] NULL, /* the place in the sequence for the element */
	   parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */
	   Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
	   NAME NVARCHAR(2000),/* the name of the object */
	   StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
	   ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
	  )
	AS
	BEGIN
	  DECLARE
	    @FirstObject INT, --the index of the first open bracket found in the JSON string
	    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
	    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
	    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
	    @Type NVARCHAR(10),--whether it denotes an object or an array
	    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
	    @Contents NVARCHAR(MAX
<think>好的,用户的问题是关于如何在SQL Server中调用API时设置请求头。我需要先回忆一下SQL Server的相关功能。记得SQL Server可以通过CLR集成或者自定义函调用外部API,但直接设置请求头可能比较困难。 首先,用户提到的示例中有一个使用dbo.FN_HTTP_POST函的例子,这个函可能是用户自定义的。根据引用[2],这个函似乎可以发送HTTP POST请求,但参里并没有提到请求头的设置。因此,可能需要修改这个自定义函来支持请求头。 接下来,我应该考虑CLR集成的方法。CLR允许用C#编存储过程,这样在发送HTTP请求时可以更灵活地设置请求头。比如使用HttpWebRequest或者HttpClient类,这些类库支持添加自定义头。引用[3]提到C#访问Web API的例子,这可能对用户有帮助。需要告诉用户如何创建CLR程序集,并在SQL Server中启用CLR,然后编C#代码来发送请求并设置头信息。 另外,用户可能需要示例代码。例如,用C#一个发送POST请求并设置Content-Type和Authorization头的函,然后部署到SQL Server中。同时,要提醒用户注意安全性和权限问题,比如启用CLR需要适当的配置。 还有,用户可能需要替代方案,比如使用中间层服务。如果直接设置请求头在SQL Server中太复杂,建议通过中间服务(如Web API)来处理,这样更安全也更灵活。引用[1]提到了Android应用直连SQL Server和通过webservice调用的对比,可能间接支持中间层的优势。 最后,要确保回答结构清晰,分步骤说明方法,提供示例,并考虑用户可能遇到的问题,比如权限、安全性以及性能影响。同时生成相关问题,帮助用户深入理解。</think>在SQL Server中直接设置HTTP请求头需要结合CLR集成或自定义函实现,以下是具体方法及示例: ### 一、通过CLR集成实现(推荐方案) 1. **启用CLR集成** ```sql EXEC sp_configure 'clr enabled', 1 RECONFIGURE ``` 2. **创建C# CLR函** ```csharp using System.Data.SqlTypes; using System.Net; using System.IO; public class HttpHelper { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString CallApiWithHeaders( SqlString url, SqlString data, SqlString contentType, SqlString headers) { var request = (HttpWebRequest)WebRequest.Create(url.Value); request.Method = "POST"; // 设置请求头 foreach (var header in headers.Value.Split(';')) { var kv = header.Split(':'); request.Headers.Add(kv[0].Trim(), kv[1].Trim()); } // 发送据 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.Value); using (var stream = request.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); } // 响应 using (var response = (HttpWebResponse)request.GetResponse()) using (var reader = new StreamReader(response.GetResponseStream())) { return new SqlString(reader.ReadToEnd()); } } } ``` 3. **注册程序集并创建函** ```sql CREATE ASSEMBLY HttpHelperAssembly FROM 'D:\assemblies\HttpHelper.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS; CREATE FUNCTION dbo.FN_API_CALL( @url NVARCHAR(4000), @data NVARCHAR(MAX), @contentType NVARCHAR(100), @headers NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS EXTERNAL NAME HttpHelperAssembly.HttpHelper.CallApiWithHeaders; ``` ### 二、使用现有扩展函(需预装组件) 若已安装类似`dbo.FN_HTTP_POST`的自定义函[^2],可通过修改参结构支持头信息: ```sql SELECT dbo.FN_HTTP_POST_EXT( 'https://api.example.com/endpoint', '{"key":"value"}', 'Content-Type:application/json;Authorization:Bearer xyz123' ) ``` ### 三、注意事项 1. 需要为SQL Server服务账户配置网络访问权限 2. CLR程序集需配置`EXTERNAL_ACCESS`或`UNSAFE`权限 3. 建议添加HTTPS证书验证处理 4. 生产环境推荐通过中间层Web Service中转调用[^1][^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值