如何处理TSQL中的错误并控制存储过程

问题描述

我从没学过T-SQL中的错误陷阱。真是有时curl.xget

SELECT @JSON = curl.xget(null,''+@GETSTRING+'') 

INSERT INTO [pcrd].[stg1_fredSeries]
           ([SeriesCode],[realStartTime],[realEndTime],[observationDate],[observationValue],[etl_dateUpdate],[ETL_UserUpdate],fk_series_id,api_url)
    SELECT 
        @SERIES_CODE AS SeriesID,*,GETDATE() AS etl_dateUpdate,'sp_get_fredSeriesPCTpe4' AS etl_userUpdate,@api_type,@GETSTRING
    FROM
        OPENJSON(@JSON,'$.observations') 

引发错误:

消息6522,级别16,状态1,过程pcrd.sp_get_fredSeriesPCType4,行72 [Batch Start Line 20]
用户定义的例程或聚合“ XGET”的执行过程中发生了.NET Framework错误:
System.Net.WebException:远程服务器返回错误:(400)错误的请求。
System.Net.WebException:
在System.Net.WebClient.DownloadDataInternal(URI地址,WebRequest和请求)
在System.Net.WebClient.DownloadString(Uri地址)
在Curl.Get(SqlChars H,SqlChars url)

这是问题还是引发错误并正在寻找Msg 6522?此插入和@GETSTRING的构建在游标提取中。游标提取中可以有BEGIN TRY吗?假设这是要走的路。

解决方法

由于您要对curl.xget进行一次调用,因此可以在try / catch中捕获错误。

fetch next from thecursor into @GETSTRING;

--better to initialize @json on each iteration
select @JSON = null; 

begin try
    SELECT @JSON = curl.xget(null,''+@GETSTRING+'') 
end try
begin catch
    --do something with the error,log etc...or just silence it
end catch

--when error for the @json assignment,@json will be null and no insertion happens
--because openjson returns no result
INSERT INTO [pcrd].[stg1_fredSeries]
SELECT 
FROM
    OPENJSON(@JSON,'$.observations')

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...