RAISERROR
Using RAISERROR¶
RAISERROR is used to return messages back to applications using the same format as a system error or warning message generated by the SQL Server Database Engine.
RAISERROR can return either:
RAISERROR can also:
Both RAISERROR and PRINT can be used to return informational or warning messages to an application. The message text returned by RAISERROR can be built using string substitution functionality similar to the printf_s function of the C standard library, whereas PRINT can only return a character string or character expression. A RAISERROR severity of 11 to 19 executed in the TRY block of a TRY…CATCH construct causes control to transfer to the associated CATCH block. Specify a severity of 10 or lower to return messages using RAISERROR without invoking a CATCH block. PRINT does not transfer control to a CATCH block.
When RAISERROR is used with the msg_id of a user-defined message in sys.messages, msg_id is returned as the SQL Server error number, or native error code. When RAISERROR is used with a msg_str instead of a msg_id, the SQL Server error number and native error number returned is 50000.
When you use RAISERROR to return a user-defined error message, use a different state number in each RAISERROR that references that error. This can help in diagnosing the errors when they are raised.
Use RAISERROR to:
Help in troubleshooting Transact-SQL code.
Check the values of data.
Return messages that contain variable text.
Cause execution to jump from a TRY block to the associated CATCH block.
Return error information from the CATCH block to the calling batch or application.
The following example substitutes the values from the DB_ID() and DB_NAME() functions in a message sent back to the application:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
This example provides the same information using a user-defined message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
The following code example shows how to use RAISERROR inside a TRY block to cause execution to jump to the associated CATCH block. It also shows how to use RAISERROR to return information about the error that invoked a CATCH block.
Note
RAISERROR can generate errors with state from 1 through 127 only. Because the Database Engine may raise errors with state 0, we recommend that you check the error state returned by ERROR_STATE before passing it as a value to the state parameter of RAISERROR.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |