Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.

Slides:



Advertisements
Similar presentations
Module 17 Tracing Access to SQL Server 2008 R2. Module Overview Capturing Activity using SQL Server Profiler Improving Performance with the Database Engine.
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
Chapter 4B: More Advanced PL/SQL Programming
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
C++ for Engineers and Scientists Third Edition
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
Module 5: Data Access. Overview Introduce database components involved in data access Introduce concepts of Transact -SQL and Procedural SQL as tools.
Topics Views Stored Procedures User Defined Functions Triggers.
Transactions and Locks Lesson 22. Skills Matrix Transaction A transaction is a series of steps that perform a logical unit of work. Transactions must.
2015 International TechNet Wiki Summit 2015 Saeid Hasani Structured Error Handling Mechanism in SQL Server 2012 & 2014.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
A Comedy of Errors Handling Errors in T-SQL Code Andrew Whettam.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Object Oriented Programming
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Module 8 Improving Performance through Nonclustered Indexes.
Store Procedures Lesson 9. Skills Matrix Stored Procedures Stored procedures in SQL Server are similar to the procedures you write in other programming.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Stored Procedures, Transactions, and Error-Handling
Module 9 Designing and Implementing Stored Procedures.
Module 9 Authenticating and Authorizing Users. Module Overview Authenticating Connections to SQL Server Authorizing Logins to Access Databases Authorization.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Module 14 Configuring Security for SQL Server Agent.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Introduction to Exception Handling and Defensive Programming.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Module 15 Monitoring SQL Server 2008 R2 with Alerts and Notifications.
Module 18 Querying XML Data in SQL Server® 2008 R2.
Module 8: Implementing Stored Procedures. Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Module 11 Creating Highly Concurrent SQL Server® 2008 R2 Applications.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Transactions and Locks A Quick Reference and Summary BIT 275.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Handling Exceptions. 2 home back first prev next last What Will I Learn? Describe several advantages of including exception handling code in PL/SQL Describe.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Module 11: Managing Transactions and Locks
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
1. Advanced SQL Functions Procedural Constructs Triggers.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
BE PREPARED Error Handling & Optimizing T-SQL Code in SQL Server 2000
16 Exception Handling.
Oracle11g: PL/SQL Programming Chapter 5 Procedures.
11 | Error Handling and Transactions
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
Introduction to Triggers
Microsoft Access Illustrated
PL/SQL Scripting in Oracle:
Overview Implementing Triggers Implementing XML Schemas.
Handling Exceptions.
Module 10: Implementing Managed Code in the Database
Objectives Define and describe transactions
Designing and Implementing Stored Procedures
Presentation transcript:

Module 12 Handling Errors in T-SQL Code

Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured Exception Handling

Lesson 1: Understanding T-SQL Error Handling Where T-SQL Errors Occur Types of Errors What's in an Error? Error Severity Demonstration 1A: Error Types and Severity

Where T-SQL Errors Occur T-SQL Errors can occur in all phases  Syntax of a statement is checked  Object names are resolved  Statement is executed Errors can be handled in two ways  Error handling code in the database engine  Error handling code in the calling application

Types of Errors CategoryNotes Syntax ErrorsExecution is never started Object Resolution ErrorsExecution is never started Statement Terminating ErrorsExecution resumes at next statement Scope TerminatingExecution resumes at next statement after statement that called the scope Batch Terminating ErrorsAborts the batch Connection Terminating ErrorsDisconnects the session Server Terminating ErrorsStops SQL Server (Rare)

What's in an Error? Errors raised by the database engine have the following attributes: AttributeDescription Error numberEach error message has a unique error number Error MessageString containing diagnostic info about the cause of the error SeverityIndicates how serious the error is StateValue used to determine the location in code at which an error occurred Procedure NameName of the stored procedure or trigger in which the error occurred (if applicable) Line NumberIndicates in which line of a batch, stored procedure, trigger or function generated the error

Error Severity The severity of an error indicates the type of problem encountered by SQL Server Severity RangeDescription 0 to 9Informational messages 10Informational messages that return status information 11 to 16Errors that can be corrected by the user 17 to 19Software errors that cannot be corrected by the user 20 to 24Serious system errors 25SQL Server service terminating error

Demonstration 1A: Error Types and Severity In this demonstration you will: See how different types of errors are returned from T-SQL statements See the types of messages that are related to severe errors Query the sys.messages view and note which errors are logged automatically

Lesson 2: Implementing T-SQL Error Handling Raising Errors Using Errors and Transactions Transaction Nesting Errors Raising Custom Errors Creating Alerts When Errors Occur Demonstration 2A: T-SQL Error Handling

Raising Errors RAISERROR  Allows raising errors in code  Is used to return errors and messages back to applications using the same format as a system error RAISERROR can return either:  A user-defined error message created with sp_addmessage  A message string specified in the RAISERROR statement int = DB_ID(); sysname = DB_NAME(); RAISERROR (N'Current database ID:%d, database name: %s.', 10, -- Severity. 1, First substitution -- Second substitution argument. int = DB_ID(); sysname = DB_NAME(); RAISERROR (N'Current database ID:%d, database name: %s.', 10, -- Severity. 1, First substitution -- Second substitution argument.

Using Returns zero if the last statement executed correctly Returns the error number if the statement generated an error Changes value on the completion of each statement RAISERROR(N'Message', 16, 1); IF <> 0 PRINT 'Error=' + AS VARCHAR(8)); GO int; RAISERROR(N'Message', 16, 1); = <> 0 PRINT 'Error=' + AS VARCHAR(8)); RAISERROR(N'Message', 16, 1); IF <> 0 PRINT 'Error=' + AS VARCHAR(8)); GO int; RAISERROR(N'Message', 16, 1); = <> 0 PRINT 'Error=' + AS VARCHAR(8));

Errors and Transactions Most errors are statement terminating errors  Statement that caused them is rolled back  Execution continues with the next statement SET XACT_ABORT  When ON, errors that would abort the T-SQL statement will abort the batch and roll back any enclosing transaction as well  When OFF (default value), in most cases only the T-SQL statement that raised the error will be rolled back  Does not affect compile and syntax errors

Transaction Nesting Errors Any ROLLBACK causes all levels of transactions to be rolled back  Nested transactions are not supported in SQL Server  Autonomous transactions are not supported in SQL Server can be used to test the transaction level Stored procedures must have the same on entry and exit or error 286 is thrown  Common situation that occurs when attempting to nest transactions

Raising Custom Errors sp_addmessage allows adding custom error messages  Error number must be or above  Can be specific to a language EXECUTE sp_addmessage 61487, 10, 'Current DatabaseID: %d, Database Name: %s'; GO int = DB_ID(); sysname = DB_NAME(); RAISERROR EXECUTE sp_addmessage 61487, 10, 'Current DatabaseID: %d, Database Name: %s'; GO int = DB_ID(); sysname = DB_NAME(); RAISERROR

Creating Alerts When Errors Occur Alerts can be raised on errors that are logged Messages (including system messages) can be altered to be alert-raising by:  Using RAISERROR() WITH LOG  Altering a message to make it logged via sp_altermessage

Demonstration 2A: T-SQL Error Handling In this demonstration, you will see: How to raise errors How severity affects errors How to add a custom error message How to raise a custom error message That custom error messages are instance-wide How to use That system error messages cannot be raised

Lesson 3: Implementing Structured Exception Handling TRY CATCH Block Programming Error Handling Functions Catchable vs. Non-catchable Errors TRY CATCH and Transactions Errors in Managed Code Demonstration 3A: Deadlock Retry

TRY CATCH Block Programming Structured exception handling is more powerful than  Allows focus on the purpose of code rather than on error handling  TRY/CATCH blocks can be nested BEGIN CATCH must follow END TRY BEGIN TRY -- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH -- Execute the error retrieval routine. EXECUTE Error.GeneralHandler; END CATCH; BEGIN TRY -- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH -- Execute the error retrieval routine. EXECUTE Error.GeneralHandler; END CATCH;

Error Handling Functions CATCH blocks have richer options for capturing error information than was available through Error functions are able to return the error information throughout the CATCH block, not just for the first statement Error handlers can be enclosed in a stored procedure for reuse CREATE PROCEDURE Error.GeneralHandler AS SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() as ErrorState, ERROR_PROCEDURE() as ErrorProcedure, ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage; GO CREATE PROCEDURE Error.GeneralHandler AS SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() as ErrorState, ERROR_PROCEDURE() as ErrorProcedure, ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage; GO

Catchable vs. Non-catchable Errors Not all errors can be caught by TRY…CATCH blocks within the same scope  Compile errors  Statement level recompilation issues  Errors that are not able to be caught in their current scope can still be caught at the next outer scope

TRY CATCH and Transactions CATCH blocks do not automatically roll back transactions Code in the catch block needs to roll back any current transaction (but only if there is a transaction) SET XACT_ABORT ON; BEGIN TRY BEGIN TRAN; -- perform work COMMIT TRAN; END TRY BEGIN CATCH IF > 0 ROLLBACK TRAN; EXEC Error.GeneralHandler; RETURN -1; END CATCH; SET XACT_ABORT ON; BEGIN TRY BEGIN TRAN; -- perform work COMMIT TRAN; END TRY BEGIN CATCH IF > 0 ROLLBACK TRAN; EXEC Error.GeneralHandler; RETURN -1; END CATCH;

Errors in Managed Code Errors can be caught using standard.NET try/catch/finally handling within the high level languages used to create managed code All errors that are passed back from managed code to T- SQL will be wrapped in a 6522 error. Errors messages can contain nested error messages. SQL CLR messages need to be unpacked to find the inner exceptions rather than the 6522 error that they are wrapped in. Managed code could execute a RAISERROR T-SQL statement via a SqlCommand object.

Demonstration 3A: Deadlock Retry In this demonstration you will see how to use structured exception handling to retry deadlock errors

Lab 12: Handling Errors in T-SQL Code Exercise 1: Replace based error handling with structured exception handling Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits) Logon information Estimated time: 45 minutes

Lab Scenario A company developer asks you for assistance with some code he is modifying. The code was written some time back and uses simple T-SQL error handling. He has heard that structured exception handling is more powerful and wishes to use it instead.

Lab Review Why do we need to test for transaction state in a CATCH block? Why do we insert a delay within the retry logic for a deadlock?

Module Review and Takeaways Review Questions Best Practices