Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error_message from SQL Server TRY.....CATCH block [duplicate]

Tags:

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='[email protected]',
    @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?

like image 755
StackTrace Avatar asked Jan 13 '14 11:01

StackTrace


People also ask

How do I get an error message in SQL Server?

When called in a CATCH block, ERROR_MESSAGE returns the complete text of the error message that caused the CATCH block to run. The text includes the values supplied for any substitutable parameters - for example, lengths, object names, or times. ERROR_MESSAGE returns NULL when called outside the scope of a CATCH block.

What is the use of @@ error in SQL Server?

Using @@ERROR to conditionally exit a procedure. The following example uses IF...ELSE statements to test @@ERROR after an DELETE statement in a stored procedure. The value of the @@ERROR variable determines the return code sent to the calling program, indicating success or failure of the procedure.

Can we have multiple catch blocks in SQL Server?

CATCH construct cannot span multiple blocks of Transact-SQL statements.

How do I find the error line in SQL Server?

ERROR_LINE returns the line number at which the error occurred. This happens regardless of the location of the ERROR_LINE call within the scope of the CATCH block, and regardless of the number of calls to ERROR_LINE .


1 Answers

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='[email protected]',
  @subject='Data Error',
  @body=@err_msg 
like image 62
Dan Avatar answered Sep 23 '22 02:09

Dan