This is a mirror of official site: http://jasper-net.blogspot.com/

Handling errors within Stored Procedures in SQL Server

| Tuesday, April 6, 2010
The robust Transact-SQL (T-SQL) syntax in SQL Server provides developers with an efficient way to handle errors within stored procedures. This article discusses the @@ERROR, SP_ADDMESSAGE, and RAISERROR functions within SQL Server.

The @@ERROR Function

Upon the completion of any T-SQL statement, SQL Server sets the @@ERROR object. If the statement was successful, @@ERROR is set to 0, otherwise it is set to the designate error code. All SQL Server error codes can be found within the master.dbo.sysmessages system table. One important thing to remember is that @@ERROR is cleared each time a statement is executed. It is a good practice to store the value within a local variable.

Anatomy of an Error

All errors raised by SQL Server return the following information.

   * Number - Each error has a unique number assigned to it.
   * Message - Contains information about the error. Many errors have substitution variables that can be placed within the text. We will cover this in the SP_ADDMESSAGE and RAISERROR sections.
   * Severity - Indicates how serious the error is. The values are between 1 and 25.
   * State - As quoted from SQL Server books on line: "Some error codes can be raised at multiple points in the source code for SQL Server. For example, an 1105' error can be raised for several different conditions. Each place the error code is raised assigns a unique state code. A Microsoft support engineer can use the state code from an error to find the location in the source code where that error code is being raised, which may provide additional ideas on how to diagnose the problem."
   * Procedure name - If the destruction occurred within a stored procedure, the name is returned.
   * Line - The line number of the demon code.

Read more: C# Corner

Posted via email from jasper22's posterous

0 comments: