如何从SQL Server TRY ..... CATCH块获取error_message

Sta*_*ace 17 t-sql sql-server

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
Run Code Online (Sandbox Code Playgroud)

我在这一行收到以下错误

@body = SELECT ERROR_MESSAGE(); 
Run Code Online (Sandbox Code Playgroud)

关键字'SELECT'附近的语法不正确.

谁知道为什么?

Dan*_*Dan 19

您不能直接将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 
Run Code Online (Sandbox Code Playgroud)


小智 7

看到这段代码.可能会在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;
Run Code Online (Sandbox Code Playgroud)


Vig*_*r A 6

请试试这个

 SET @body = ERROR_MESSAGE()
Run Code Online (Sandbox Code Playgroud)