SQL Server Statement Overview: Raiseerror
SQL Server Statement Overview: Raiseerror
The RAISERROR statement allows you to generate your own error messages and return
these messages back to the application using the same format as a system error or warning
message generated by SQL Server Database Engine. In addition, the RAISERROR statement
allows you to set a specific message id, level of severity, and state for the error messages.
The following illustrates the syntax of the RAISERROR statement:
1 RAISERROR ( { message_id | message_text | @local_variable }
2 { ,severity ,state }
3 [ ,argument [ ,...n ] ] )
4 [ WITH option [ ,...n ] ];
Let’s examine the syntax of the RAISERROR for better understanding.
message_id
The message_id is a user-defined error message number stored in
the sys.messages catalog view.
To add a new user-defined error message number, you use the stored
procedure sp_addmessage. A user-defined error message number should be greater than
50,000. By default, the RAISERROR statement uses the message_id 50,000 for raising an
error.
The following statement adds a custom error message to the sys.messages view:
1 EXEC sp_addmessage
2 @msgnum = 50005,
3 @severity = 1,
4 @msgtext = 'A custom error message';
To verify the insert, you use the following query:
1 SELECT
2 *
3 FROM
4 sys.messages
5 WHERE
6 message_id = 50005;
To use this message_id, you execute the RAISEERROR statement as follows:
1 RAISERROR ( 50005,1,1)
Here is the output:
WITH option
The option can be LOG, NOWAIT, or SETERROR:
WITH LOG logs the error in the error log and application log for the instance of the
SQL Server Database Engine.
WITH NOWAIT sends the error message to the client immediately.
WITH SETERROR sets the ERROR_NUMBER and @@ERROR values to message_id or
50000, regardless of the severity level.
SQL Server RAISERROR examples
Let’s take some examples of using the RAISERROR statement to get a better understanding.
A) Using SQL Server RAISERROR with TRY CATCH block example
In this example, we use the RAISERROR inside a TRY block to cause execution to jump to the
associated CATCH block. Inside the CATCH block, we use the RAISERROR to return the error
information that invoked the CATCH block.
1 DECLARE
2 @ErrorMessage NVARCHAR(4000),
3 @ErrorSeverity INT,
4 @ErrorState INT;
5
6 BEGIN TRY
7 RAISERROR('Error occurred in the TRY block.', 17, 1);
8 END TRY
9 BEGIN CATCH
10 SELECT
11 @ErrorMessage = ERROR_MESSAGE(),
12 @ErrorSeverity = ERROR_SEVERITY(),
13 @ErrorState = ERROR_STATE();
14
15 -- return the error inside the CATCH block
16 RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
17 END CATCH;
Here is the output: