Error Handling Stored Procedures
Contents |
Errors in SQL Server 2012 03 January 2013Handling Errors in SQL Server 2012The error handling of SQL Server has always been somewhat mysterious. Now at last, the THROW statement has been sql server stored procedures error handling included in SQL Server 2012 that, combined with the TRY ... CATCH block, makes error error handling in stored procedure sql server 2008 handling far easier. Robert Sheldon explains all. 194 14 Robert Sheldon Since the release of SQL Server 2005, you've been able to
Error Handling In Stored Procedure Sql Server 2012
handle errors in your T-SQL code by including a TRY…CATCH block that controls the flow of your script should an error occur, similar to how procedural languages have traditionally handled errors. The TRY…CATCH block makes it
Error Handling In Stored Procedure Oracle
easy to return or audit error-related data, as well as take other actions. And within the block-specifically, the CATCH portion-you've been able to include a RAISERROR statement in order to re-throw error-related data to the calling application. However, with the release of SQL Server 2012, you now have a replacement for RAISERROR, the THROW statement, which makes it easier than ever to capture the error-related data. In this article, we'll look at mysql stored procedure error handling the TRY…CATCH block used with both the RAISERROR and THROW statements. The examples are based on a table I created in the AdventureWorks2012 sample database, on a local instance of SQL Server 2012. Listing 1 shows the T-SQL script I used to create the LastYearSales table. 123456789101112131415161718 USE AdventureWorks2012;GOIF OBJECT_ID('LastYearSales', 'U') IS NOT NULLDROP TABLE LastYearSales;GOSELECTBusinessEntityID AS SalesPersonID,FirstName + ' ' + LastName AS FullName,SalesLastYearINTOLastYearSalesFROMSales.vSalesPersonWHERESalesLastYear > 0;GO Listing 1: Creating the LastYearSales table The script should be fairly straightforward. I use a SELECT…INTO statement to retrieve data from the Sales.vSalesPerson view and insert it into the newly created table. However, to demonstrate how to handle errors, we need to add one more element to our table: a check constraint that ensures the SalesLastYear value is never less than zero. Listing 2 shows the ALTERTABLE statement I used to add the constraint. 123 ALTER TABLE LastYearSalesADD CONSTRAINT ckSalesTotal CHECK (SalesLastYear >= 0);GO Listing 2: Adding a check constraint to the LastYearSales table The constraint makes it easy to generate an error when updating the table. All I have to do is try to add a negative amount to the SalesLastYear column, an amount large enough to cause SQL Server to throw an error. Once we've created our table and added the check constraint, we have the en
This part is also available in a Spanish translation by Geovanny Hernandez. Introduction This article is the first in
Stored Procedure Error Handling Best Practices
a series of three about error and transaction handling in SQL Server. sql stored procedure try catch The aim of this first article is to give you a jumpstart with error handling by showing sql server stored procedure error handling best practices you a basic pattern which is good for the main bulk of your code. This part is written with the innocent and inexperienced reader in mind, why I am https://www.simple-talk.com/sql/database-administration/handling-errors-in-sql-server-2012/ intentionally silent on many details. The purpose here is to tell you how without dwelling much on why. If you take my words for your truth, you may prefer to only read this part and save the other two for a later point in your career. On the other hand, if you question my guidelines, you certainly http://www.sommarskog.se/error_handling/Part1.html need to read the other two parts, where I go into much deeper detail exploring the very confusing world of error and transaction handling in SQL Server. Parts Two and Three, as well as the three appendixes, are directed towards readers with a more general programming experience, although necessarily not with SQL Server. This first article is short; Parts Two and Three are considerably longer. Table of Contents Introduction Index of All Error-Handling Articles Why Error Handling? Essential Commands TRY-CATCH SET XACT_ABORT ON General Pattern for Error Handling Three Ways to Reraise the Error Using error_handler_sp Using ;THROW Using SqlEventLog Final Remarks End of Part One Revision History Index of All Error-Handling Articles Here follows a list of all articles in this series: Part One - Jumpstart Error Handling (this article). Part Two - Commands and Mechanisms. Part Three - Implementation. Appendix 1 - Linked Servers. (Extends Part Two.) Appendix 2 - CLR. (Extends both Parts Two and Three.) Appendix 3 - Service Broker. (Extends Part Three.) All the articles above
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss http://stackoverflow.com/questions/12403221/error-handling-in-sql-server-stored-procedures the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping stored procedure each other. Join them; it only takes a minute: Sign up Error Handling in SQL Server Stored Procedures up vote 2 down vote favorite I have a fairly complex SP (logic wise) with nested IF BEGIN END ELSE, there are multiple end points in this nested logic where the logic fails and I RAISERROR and two places that error handling in result in success and SQL being actioned. How, at the end of the SP can I trap the errors and do a IF Error Count>0 THEN ROLLBACK DECLARE @errCount int=0 DECLARE @DataSetCount int=0 DECLARE @countCurrent int=0 DECLARE @countHistorical int=0 IF (isnumeric(@DataSetID)=(0) OR @DataSetID=(0)) BEGIN RAISERROR('The DataSet specfied does not appear to be valid', 5, 1) END ELSE IF (@Destination='C' OR @Destination='H') BEGIN if Exists (SELECT NULL from tblOpportunityDataSets where DataSetID=@DataSetID) BEGIN SET @countCurrent=(SELECT COUNT(1) from tblOptyRecordsCurrent where DataSetID=@DataSetID) SET @countHistorical=(SELECT COUNT(1) from tblOptyRecordsHistorical where DataSetID=@DataSetID) IF @destination='C' BEGIN if @countCurrent>0 BEGIN RAISERROR('There are already existing records in the Current Tables for the specified DataSet', 5, 1) END ELSE if @countHistorical=0 BEGIN RAISERROR('There do not appear to be any records in the Historical Tables to transfer for the specified Dataset', 5, 1) END ELSE BEGIN -- ENTER TRANSFER CODE INSERT INTO tblRecordsHistorical ( X, Y, Z ) SELECT X, Y, Z FROM tblA WHERE x=y -- Check that record count in both tables match SET @countCurrent=(SELECT COUNT(1) from tblOptyRecordsCurrent where DataSetID=@DataSetID) SET @countHistorical=(S