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

时间:2014-01-13 11:24:04

标签: sql-server tsql

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”附近的语法不正确。

任何人都知道为什么?

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分:6)

请试试这个

 SET @body = ERROR_MESSAGE()

答案 2 :(得分:6)

请参阅此代码块。在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;