| Previous | Table of Contents | Next |
When something goes wrongperhaps the procedure expected the user to supply an invoice number, and the user failed to do soyou can raise custom error messages that get returned to the user.
I mentioned earlier that the SQL Server keeps track of all system errors in a system table called sysmessages. This table resides in the master database. The SQL Server has provided a system stored procedure to allow you to add your own messages to the sysmessages table.
This stored procedure is sp_addmessage. Here is an example of how you might add a message to sysmessages:

exec sp_addmessage 60000, 11, Customer ID not found in table
aq_customer
Once this message has been added to the other messages, you can raise the error by providing its number to the RAISERROR function:

raiserror (60000, 11, 1)

Msg 60000, Severity 11, State 1
Customer ID not found in table aq_customer
This example uses a different method for raising an error, providing the number instead of static text for the error. This method allows a defined error number to be passed back to the user.
Guidelines for Defining Your Own Errors
When you define your own error messages, there are a few things to keep in mind:
Other Options for raiserror
Here is the full syntax statement for RAISERROR:

raiserror(msg_string, severity, state [WITH LOG])
raiserror (msg_id, severity, state [, arg1[, arg2 [, arg3...]]]
[WITH LOG])
The WITH LOG option is available only to system administrators. Use of this option will provide the error to the users screen and also copy it to the system log.
For the second type of RAISERROR, arguments are allowed. To use this, consider this example:

exec sp_addmessage 60102, 14, Customer %s does not
exist in invoices.

raiserror(60102, 14, 1, Katrina VanAllen)

Msg 60102, Severity 14, State 1
Customer Katrina VanAllen does not exist in invoices.
The capability to pass arguments to error messages greatly increases the flexibility of the error system.
print Statement
Like RAISERROR, the PRINT statement returns a message to the user. PRINT statements are commonly used in stored procedures or in SQL code to communicate a non-critical message to the user. In applications, PRINT statements should be displayed in an unobtrusive manner for the user to observe. This example shows a simple PRINT statement:

Print The sky is falling!

The sky is falling!
Note: If you program DB-Library applications, a PRINT statement will come through to your message handler along with errors generated by RAISERROR. A print statement will always generate an error number and severity of zero.
In this section, I describe a few of the errors I see newcomers to SQL running into. Sometimes the error messages are not terribly communicative.
select UserID from customer
| Previous | Table of Contents | Next |