【问题标题】:How to handle an error in TSQL and take control of the stored procedure如何处理 TSQL 中的错误并控制存储过程
【发布时间】:2020-09-10 05:50:51
【问题描述】:

我从未学习过 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 行 [批处理开始第 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)

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

【问题讨论】:

    标签: json sql-server tsql error-handling


    【解决方案1】:

    由于您对 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2012-03-23
      • 2020-03-08
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多