asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Transact-SQL Improves Database Error-Handling
By Carvin Wilson
Rating: 3.6 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Overview

    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.

    There are two classes of error messages in SQL Server -- fatal and nonfatal. Remember that fatal errors will kill the client connection. Creating stored procedures that cause fatal errors is a good way to get rid of slacking programmers or consultants.

    SP_ADDMESSAGE

    Use the sp_addmessage feature to add your own customized messages. The following information is given about each parameter:

    • @msgnum (smallint) - This is the message ID. All user-defined messages start with 50001. The combination of this parameter and language must be unique.

    • @severity (smallint) - The severity level is between 1 and 25. Only the system administrator can add a message above the level of 18. Messages below the age of 18 are still considered to be "toddlers," and anyone can add them.

    • @msgtext nvarchar(255) - This is the text of the error message. Variables can be used within the text. This functionality is similar to the printf feature within C.

    • @lang - Since SQL Server can support different languages, you can store your error messages in multiple languages. This will help greatly when we start joint-developing with people from different planets. If left NULL, it will default to the default language of the current session.

    • @with_log varchar(5) - This value can be TRUE or FALSE. If you set this parameter to "TRUE," then messages are written to the Windows and SQL Server application log.

    • @replace varchar(7) - This allows you to replace an existing error message with a new message text and severity level. The default is NULL. This is a great way to tick the database administrator off!

    RAISERROR

    You can also use the RAISERROR command to create an error message. RAISERROR can send the error message information back to a client application.

    The following information is given about the parameters.

    • @msg_id - This is the message ID of your user-defined message. All adhoc error messages are given the message ID of 50000.

    • @msg_str - The message can have up to 400 characters. If the message contains more than 400 characters, only the first 397 will be displayed and an ellipsis will be added to indicate that the message has been cut. You can also use formatting values within the message text. An example of this is given below.

    • @argument - These are values to be used within the message text.

    • @WITH - Acceptable values are LOG, NOWAIT, and SETERROR. The LOG option logs the error to the server and application log; NOWAIT sends the messages immediately back to the client application; and SETERROR sets the @@ERROR value to the @MSG_ID or 50000, regardless of the serverity level.

    Sample Code

    The User-defined Error Message

    For the formatting, I will use %s for strings and %I for integers. This functionality is similar to the printf function in C. I know you still have those C notes from college somewhere!

    USE master
    EXEC sp_addmessage 
      50010, /*message id*/
      16, /*severity level*/ 
      'Error in stored procedure %s', /*message text*/
      'us_english', /*language*/
      'FALSE', /*log this error*/
       NULL /*replace existing error*/
    

    Using RAISERROR to Call the Error Message

    I will use the pubs database for this demonstration.

    Step 1. Create the following procedure.

    CREATE PROCEDURE spDemo
    AS BEGIN
     SELECT TOP 10 * FROM AUTHORS
     IF @@ROWCOUNT < 11 
      RAISERROR (50010,12,1,'Raise Error Demo')
    END 
    
    Step 2. Execute the procedure.
    Exec spDemo
    
    You will then get the following error message.
    "Server: Msg 50010, Level 12, State 1, Procedure spDemo, Line 5
    Error in stored procedure Raise Error Demo"
    
    Here is another example of using RAISERROR without a user-defined message.
    RAISERROR ('An error occurred because we are overworked and underpaid!',10,1)
    

    Real-World Use of @@ERROR and RAISERROR

    Although common practice tells us that user validation goes on the front end, most database administrators (DBA) implement developer validation of the back -end. Experience has taught them that we cannot always be trusted to implement requirements correctly. Another valid reason would be that your database is being used by several different applications, and as an added precaution the DBA has decided to implement database-level validation.

    Step 1. Create the following procedure in the pubs database.

    
    CREATE PROCEDURE spDiscounts(@TYPE VARCHAR(40),
     @STORE CHAR(4),@LOW SMALLINT, @HIGH SMALLINT, @DISCOUNT NUMERIC(9,2))
    AS BEGIN
    IF @DISCOUNT > 7 
     BEGIN
      RAISERROR ('You entered %d, the discount can not be greater than 7.', 10, 1, @DISCOUNT)
     END
    ELSE
     BEGIN
      BEGIN TRANSACTION
      INSERT INTO DISCOUNTS(DISCOUNTTYPE, STOR_ID, LOWQTY, HIGHQTY, DISCOUNT)
      VALUES (@TYPE,@STORE,@LOW,@HIGH,@DISCOUNT)
      IF @@ERROR <> 0
       ROLLBACK TRANSACTION
      ELSE 
       COMMIT TRANSACTION
      END 
    END
    
    
    Step 2. Execute the following procedure.
    exec spDiscounts 'My Discount', NULL, 10, 100, 12
    
    You will receive the following error message:
    "You entered 12; the discount cannot be greater than 7."
    
    Returning logical error messages like this to the client application will save hours of head scratching.

    Summary

    I hope I have spawned a few ideas of what you can do with @@ERROR, SP_ADDMESSAGE, and RAISERROR. T-SQL gives developers a very powerful tool to use when creating stored procedures. You can find well-written documentation within the SQL Server books on line. If you have any problems, questions, or comments about this article please email me.

    About the Author

    Carvin Wilson is the president/CEO of Harborview Solutions, a software consulting firm in Gig Harbor, Washington. He has over 12 years of experience creating client/server, Internet, and multitiered enterprise solutions. He enjoys writing and sharing his abilities with other programmers. His hobbies consist of golf, guitars, and playing computer games. Carvin can be reached at cwilson@harborviewsolutions.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    CustomError 2.0 for IIS
    When errors occur on a Web site, they should be handled in a way that helps the user to get back on track. Unfortunately, setting up customized error pages in IIS usually requires something many Web developers lack -- access to and familiarity with the Web server's administrative interface. With CustomError for IIS, developers can add error pages, coded by hand or created in their favorite editor, by simply uploading them to a designated directory. No administrator intervention is required.
    [Top]
    Other Articles
    Sep 22, 2004 - Unit Test - Testing with NUnit Framework
    Kamran Qamar introduces unit testing with NUnit and offers some best practices, tips, and tricks.
    [Read This Article]  [Top]
    Aug 10, 2004 - Implementing and Promoting Daily Builds
    Automatic daily builds is a well known software engineering best practice. This article introduces a strategy for implementing and promoting daily builds and offers tips and tricks for preventing and fixing breaks.
    [Read This Article]  [Top]
    Jun 21, 2004 - Using Open Source .NET Tools for Sophisticated Builds
    Building an application can be more than pressing F5. With an increasing number of quality packages being released, developers for the .NET platform now have options to create a very sophisticated build process. Aaron Junod describes a sample build environment and shows how a number of tools can work together to make reliable, predictable, and value-added builds.
    [Read This Article]  [Top]
    Jun 18, 2003 - Online Database Functions Testing Tool
    This short article provides source code for a classic ASP online database functions testing application and shows how to configure and use the tool for either SQL Server or Oracle.
    [Read This Article]  [Top]
    Jan 2, 2003 - Web Application Error Handling in ASP.NET
    One of many improvements ASP.NET brings to the development table is in error handling. Adam Tuliper whips up a simple ASP.NET solution for handling those pesky and unexpected post-production errors.
    [Read This Article]  [Top]
    Sep 10, 2002 - Tracing in .NET and Implementing Your Own Trace Listeners
    Mansoor Ahmed Siddiqui explains debugging and tracing and shows how to create custom trace listeners to help ensure hassle-free development.
    [Read This Article]  [Top]
    Sep 5, 2001 - Firing Events in a Shared Hosting Environment
    Firing events on a Web server is an easy task. However most of the easy solutions require you to have your own dedicated IIS or SQL Server on the Internet to play with, a privilege not shared by many. In this article, Matthew Muller shows you how to get the same functionality in a shared hosting environment.
    [Read This Article]  [Top]
    May 25, 2001 - Avoiding a Type Mismatch Error When Using ByRef with ASP and COM
    Unlike programming inside a complete VB system, when using ByRef with ASP and COM, a complication arises because ASP's VBScript is not typed, but the component's VB is typed. This article will briefly explain how ByRef can be used with ASP and COM.
    [Read This Article]  [Top]
    Apr 18, 2001 - Error Reporting - IIS 5.0
    The script in Mark Newlands' article this week handles how errors are displayed and logged. It can capture all values in use at the time (e.g. form, querystring, session,and application level) and records them if you set a Boolean value to do so - displays custom HTML if required. Sends email, logs to database, and/or text file.
    [Read This Article]  [Top]
    Feb 2, 2001 - Solving a Caching And Expiring Problem
    Read what advice members of the 15Seconds Discussion list had to offer on forcing pages to refesh, even when the user hits the back button.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    IBM eBook: Planning a Service Oriented Architecture
    IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
    Intel Go Parallel Article: Getting Started with TBB on Windows
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Avaya Article: How to Feed Data into the Avaya Event Processor
    IBM Article: Developing a Software Policy for Your Organization
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    Intel Go Parallel Article: Intel Threading Tools and OpenMP
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    HP Video: StorageWorks EVA4400 and Oracle
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
    IBM Article: Enterprise Search--Do You Know What's Out There?
    HP Demo: StorageWorks EVA4400
    Microsoft Article: The Progress and Promise of Deep Zoom
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES