21
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

I am getting the following error at this line

@body = SELECT ERROR_MESSAGE(); 

Incorrect syntax near the keyword 'SELECT'.

Any one know why?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
StackTrace
  • 9,190
  • 36
  • 114
  • 202

3 Answers3

22

You can not issue a SELECT statement directly into the parameter of a stored procedure. Do something like this instead:

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 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dan
  • 10,480
  • 23
  • 49
10

See this block of code. Might help you a little bit in exception handling at Sql end.

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;
6

Please Try this

 SET @body = ERROR_MESSAGE()
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115