【问题标题】:How to get error_message from SQL Server TRY.....CATCH block [duplicate]如何从 SQL Server TRY .....CATCH 块中获取 error_message [重复]
【发布时间】:2014-01-13 11:24:04
【问题描述】:
BEGIN TRY
    BEGIN TRANSACTION 
      --Lots of T-SQL Code here
    COMMIT
END TRY
BEGIN CATCH
    ROLLBACK
    USE  [msdb];
    EXEC sp_send_dbmail 
    @profile_name='Mail Profile',
    @recipients='myEmail@mydomain.org',
    @subject='Data Error',
    @body =  SELECT ERROR_MESSAGE();
END CATCH

我在这一行收到以下错误

@body = SELECT ERROR_MESSAGE(); 

关键字“SELECT”附近的语法不正确。

有人知道为什么吗?

【问题讨论】:

标签: sql-server tsql


【解决方案1】:

您不能直接向存储过程的参数发出 SELECT 语句。改为这样做:

DECLARE @err_msg AS NVARCHAR(MAX);

SET @err_msg = ERROR_MESSAGE();

EXEC sp_send_dbmail
  @profile_name='your Mail Profile here',
  @recipients='myEmail@mydomain.org',
  @subject='Data Error',
  @body=@err_msg 

【讨论】:

    【解决方案2】:

    查看此代码块。可能对你在 Sql 端的异常处理有所帮助。

    BEGIN TRY
        -- RAISERROR with severity 11-19 will cause execution to 
        -- jump to the CATCH block.
        RAISERROR ('Error raised in TRY block.', -- Message text.
                   16, -- Severity.
                   1 -- State.
                   );
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;
    
        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();
    
        -- Use RAISERROR inside the CATCH block to return error
        -- information about the original error that caused
        -- execution to jump to the CATCH block.
       -- RAISERROR (@ErrorMessage, -- Message text.
                 --  @ErrorSeverity, -- Severity.
                 --  @ErrorState -- State.
                 --  );
    
    
    
    EXEC sp_send_dbmail 
        @profile_name='Mail Profile',
        @recipients='myEmail@mydomain.org',
        @subject='Error Refreshing PMT Database',
        @body =  @ErrorMessage;
    END CATCH;
    

    【讨论】:

      【解决方案3】:

      请试试这个

       SET @body = ERROR_MESSAGE()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-28
        • 1970-01-01
        相关资源
        最近更新 更多