【问题标题】:Writing SQL runtime/syntax errors to a text file将 SQL 运行时/语法错误写入文本文件
【发布时间】:2023-01-13 03:22:31
【问题描述】:

如果 SQL 存储过程中存在语法或运行时错误,我想生成一个文本文件。 例如,我想在调用过程时创建一个包含此信息的文本文件,如果生成以下错误:

消息 8114,级别 16,状态 5,过程 sp_LoadKAD_UAT,第 94 行 [批处理开始第 94 行] 将数据类型 varchar 转换为 float 时出错。

我没有使用任何其他前端工具。我需要 SQL Server 中的解决方案。 我正在使用 Microsoft SQL Server 2017

我已经对 TRY 和 catch 块以及 @@Error 进行了研究,但我还没有找到解决方案。

【问题讨论】:

  • 您可以从 error_message() 的 catch 块中获取错误。您可以将其插入到日志表中,您可以从中查询或导出数据。如果您真的必须在 sql server 中完成所有操作,可以使用实用程序函数脚本使用 scripting.filesystemobject 写入文件。
  • 使用 try_convert( float, YourColumn ) ... 如果转换失败,这将返回 NULL 而不是抛出错误。现在,如果您想查看有问题的行 Select * from YourTable Where try_convert( float, YourColumn ) is NULL and YourColumn is not NULL

标签: sql-server error-handling runtime-error


【解决方案1】:

您可以使用 TRY 和 CATCH 块来处理 SQL 存储过程中的错误。 TRY 块包含可能产生错误的代码,CATCH 块包含处理 TRY 块中出现的任何错误的代码。

要在发生错误时创建包含错误信息的文本文件,可以使用xp_cmdshell 扩展存储过程运行命令行实用程序“echo”,将错误信息写入文本文件。

下面是一个示例,说明如何将 TRY 和 CATCH 块与 xp_cmdshell 结合使用来创建包含错误信息的文本文件:

    BEGIN TRY
  -- code that might generate an error
END TRY
BEGIN CATCH
  DECLARE @ErrorMessage NVARCHAR(4000);
  DECLARE @ErrorSeverity INT;
  DECLARE @ErrorState INT;
  DECLARE @ErrorLine INT;
  DECLARE @ErrorNumber INT;
  DECLARE @ErrorProcedure NVARCHAR(200);
  DECLARE @ErrorLineNumber INT;

  SELECT 
      @ErrorLineNumber = ERROR_LINE(),
      @ErrorProcedure = ERROR_PROCEDURE(),
      @ErrorNumber = ERROR_NUMBER(),
      @ErrorLine = ERROR_LINE(),
      @ErrorSeverity = ERROR_SEVERITY(),
      @ErrorState = ERROR_STATE(),
      @ErrorMessage = ERROR_MESSAGE();

  -- create the text file with the error information
  EXEC xp_cmdshell 'echo Error Number: ' + CAST(@ErrorNumber AS NVARCHAR(10)) + ', Error Message: ' + @ErrorMessage + ', Error Procedure: ' + @ErrorProcedure + ', Error Line Number: ' + CAST(@ErrorLineNumber AS NVARCHAR(10)) + '>> C:errors.txt';
END CATCH

此示例捕获错误信息并将其写入位于 C 驱动器中的名为 errors.txt 的文本文件。您可以根据需要更改文本文件的位置。

请注意,xp_cmdshell 是一个 SQL Server 扩展存储过程,允许您从 SQL Server 中运行命令提示符命令,因此您可能需要通过执行以下命令在 SQL Server 2017 实例上启用它:

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'xp_cmdshell', 1;  
GO  
RECONFIGURE;  
GO  

【讨论】:

    【解决方案2】:

    使用 Try Catch 块,您可以处理错误消息并插入到任何临时表中。

    Declare @Catcherror as Table (Errornumber int, Errormessage varchar(100))
    
    BEGIN TRY 
        Declare @num1 as int=1, @num2 as int = 0, @result as int
        set @result= @num1/@num2
    
    end TRY
    BEGIN CATCH
        insert into @Catcherror (Errornumber, Errormessage)
        Select ERROR_NUMBER() as Errornumber, ERROR_MESSAGE() as Errormessage
    end CATCH
    
    Select * from @Catcherror
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      相关资源
      最近更新 更多