A Comedy of Errors Handling Errors in T-SQL Code Andrew Whettam.

Slides:



Advertisements
Similar presentations
Oracle PL/SQL IV Exceptions Packages.
Advertisements

Manipulating Data Schedule: Timing Topic 60 minutes Lecture
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Transaction Processing. Objectives After completing this lesson, you should be able to do the following: –Define transactions effectively for an application.
Transaction Simon Cho. Who am I? Simon Cho Blog : Simonsql.com All Presentation and script will be on My.
Transactions and Locking Rose-Hulman Institute of Technology Curt Clifton.
Module 15: Managing Transactions and Locks. Overview Introduction to Transactions and Locks Managing Transactions SQL Server Locking Managing Locks.
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
Chapter 8 : Transaction Management. u Function and importance of transactions. u Properties of transactions. u Concurrency Control – Meaning of serializability.
Transaction Management WXES 2103 Database. Content What is transaction Transaction properties Transaction management with SQL Transaction log DBMS Transaction.
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Module 5: Data Access. Overview Introduce database components involved in data access Introduce concepts of Transact -SQL and Procedural SQL as tools.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
INTRODUCTION TO TRANSACTION PROCESSING CHAPTER 21 (6/E) CHAPTER 17 (5/E)
Managing Transaction and Lock Vu Tuyet Trinh Hanoi University of Technology 1.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Object Oriented Programming
Transactions and Exception Handling Eric Allsop SQLBits 6 th October 2007.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
By Lecturer / Aisha Dawood 1.  You can control the number of dispatcher processes in the instance. Unlike the number of shared servers, the number of.
Store Procedures Lesson 9. Skills Matrix Stored Procedures Stored procedures in SQL Server are similar to the procedures you write in other programming.
Stored Procedures, Transactions, and Error-Handling
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Chapter 9 Selecting, Updating, and Deleting Data Syed Rizvi.
BA372 Stored Procedures and Triggers Lab. What needs to be done to change a customer’s credit limit? Who am I? May I? Do it Log it Display A database.
Chapter 15 Recovery. Topics in this Chapter Transactions Transaction Recovery System Recovery Media Recovery Two-Phase Commit SQL Facilities.
Introduction to Exception Handling and Defensive Programming.
CSIT 313 DB PROGRAMMING EXCEPTION HANDLING. In PL/SQL, an error condition is called an exception. An exception can be either –internally defined (by the.
How transactions work A transaction groups a set of Transact-SQL statements so that they are treated as a unit. Either all statements in the group are.
Module 8: Implementing Stored Procedures. Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans.
Chapter 15 Recovery. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.15-2 Topics in this Chapter Transactions Transaction Recovery System.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Transactions and Locks A Quick Reference and Summary BIT 275.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Advanced Database- Dr. Arasteh1 Advanced Database Bahman Arasteh ( Ph.D, Software Engineering ) Department of Software Engineering, Azad University of.
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
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Module 14: Managing Transactions and Locks. Overview Introducing Transactions and Locks Managing Transactions Understanding SQL Server Locking Architecture.
Delete Data Database Administration Fundamentals LESSON 3.4.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
BE PREPARED Error Handling & Optimizing T-SQL Code in SQL Server 2000
Running a Forms Developer Application
Web Technologies IT230 Dr Mohamed Habib.
11 | Error Handling and Transactions
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
LAB: Web-scale Data Management on a Cloud
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Transactions, Locking and Query Optimisation
The PROCESS of Queries John Deardurff
The PROCESS of Queries John Deardurff Website: ThatAwesomeTrainer.com
On transactions, and Atomic Operations
The PROCESS of Queries John Deardurff
Batches, Transactions, & Errors
Chapter 8 Advanced SQL.
Objectives Define and describe transactions
STRUCTURE OF PRESENTATION :
Chapter 11 Managing Databases with SQL Server 2000
Server-Side Programming
Presentation transcript:

A Comedy of Errors Handling Errors in T-SQL Code Andrew Whettam

Currently a Senior Consultant with IMGROUP Formerly Database Team Leader at 3M, Capital One MI Lead Contact: Or: Or: uk.linkedin.com/AndrewWhettam

Agenda Handling Errors - OverviewTerminology and BackgroundTransactionsError Handling in SQL Server VersionsSuggested Approach

HANDLING ERRORS 1. How the Application Behaves2. What is Communicated and How

Error Handling Behaviour 1. Roll everything back to a consistent state E.g. bank account transaction 2. Leave everything “as-is” ready for investigation E.g. ETL (Extract, Transform, Load) 3. Perform custom operations to allow application to continue Possible error handling behaviour scenarios include:

Error Messages 1. Who is the message for? End users (in application code please) IT Support (1st technical contact in many organisations) DBAs Developers 2. What does each need to know? End users - what they can do to fix OR call IT Support IT Support - what is the cause: Network, DNS, SMTP, Server, Application, Database DBAs / Developers - detail of exactly what happened: Precise details, module name(s), location in code

TERMINOLOGY & BACKGROUND

Statements and Batches -- 1ST BATCH SELECT * FROM dbo.Test; -- 1st statement INSERT dbo.Test (Col1) VALUES ('blah'); -- 2nd statement UPDATE dbo.Test SET Col1 = 'blah blah'; -- 3rd statement GO 5-- Batch separator with count -- 2ND BATCH SELECT * FROM dbo.Test; -- 1st statement TRUNCATE TABLE dbo.Test; -- 2nd statement GO-- Batch separator

Some exceptions cause different behaviour, depending on whether the error occurs in the same Scope or a different Scope Scope Each of these is a separate Scope: Calling CodeOuter Stored ProcInner Stored Proc Dynamic SQL (inside inner stored proc) Errors bubble up

TRIGGER CONTEXT Trigger Context exists: 1. In a trigger 2. In other code called by a trigger (proc, function, dynamic SQL) All errors terminate the batch and roll back the transaction, except: RAISERROR Error 266 Errors cause the behaviours described in the following slides OTHER CODE Context

Statement- Level Batch-Level Connection- Level Server-Level Batch-level exceptions can behave in a number of different ways, depending on Scope: Exception Levels Parsing Scope Resolution Standard Batch-level

DEMO Exception Levels

Error levels Information only Errors that can be corrected by the user More serious (out of memory, disk space etc.) Fatal connection and server-level exceptions Nominal rules (these don’t appear to be followed strictly!)

TRANSACTIONS

ACID Atomic Within a transaction, DML operations succeed or fail as a unit Some operations (e.g. reads) may be affected by other transactions Consistent The database is left in a state that does not violate active constraints Isolated There is a degree of isolation, depending on the isolation level Locking etc. may affect other operations Durable Applies to persistent (recoverable) user data SQL Server provides ACID guarantees – to a degree!

Implicit / Explicit Transactions Explicit transactions (default) Started with a BEGIN TRAN statement Ended with either COMMIT or ROLLBACK Implicit transactions A new transaction is automatically started immediately after a commit or rollback (BEGIN TRAN not required) COMMIT or ROLLBACK still required Certain statements and ANSI settings will automatically turn on implicit transactions (e.g. When SET ANSI_DEFAULTS is ON, SET IMPLICIT_TRANSACTIONS is ON) SET IMPLICIT_TRANSACTIONS ON; SET IMPLICIT_TRANSACTIONS OFF;

BEGIN TRAN Marks a logically consistent point to be the start of a local transaction Increments the transaction count by 1 BEGIN { TRAN | TRANSACTION } [ { transaction_name } [ WITH MARK [ 'description' ] ] ] [ ; ] Savepoint Transaction Name Only with outermost transaction or savepoint WITH MARK Specifies that the transaction is marked in the log Allows for restoring a transaction log to a named mark

Nested Transactions Begin Transaction 1, transaction count = 1 Calling code Begin Transaction 2, transaction count = 2 Outer stored proc Begin Transaction 3, transaction count = 3 Commit Transaction 3, transaction count = 2 Inner stored proc Commit Transaction 2, transaction count = 1 Outer stored proc Commit Transaction 1, transaction count = 0 Data finally committed to disk Calling code

DEMO Transactions

More Transaction Code Shows the number of open transactions (i.e. nesting level) COMMIT Decreases transaction count by 1 Transaction is committed only when transaction count reaches 0 ROLLBACK Reduces transaction count to 0 in 1 hit Only use in outer transaction if nested (including calling applications) XACT_STATE() 1 - Transaction(s) is active 0 - There is no transaction -1 - Active transaction is uncomittable

XACT_ABORT When on, run-time errors cause entire transaction to roll back I.e. XACT_ABORT ON makes most statement-level, parsing and scope resolution exceptions behave like batch-level exceptions SET XACT_ABORT OFF; (Default setting) SET XACT_ABORT ON; Exceptions: Errors raised using RAISERROR Some Compilation Errors, but not all Transaction count mismatch errors

XACT_ABORT – cont. Triggers: XACT_ABORT is on by default Compatibility-level setting affects behaviour of Ability to set XACT_ABORT off in triggers (not possible pre 100) Behaviour of OUTPUT clause Setting is set at run-time, not parse time Other considerations

DEMO XACT_ABORT

ERROR HANDLING

Messages System messages stored in sys.messages Custom messages can be added using sp_addmessage Stored in sys.messages Message ID must be an integer between 50,001 and 2,147,483,647 Sys.messages

SQL Server 2000

and Both return a value for the previous statement returns 0 if the previous statement ran successfully otherwise an error number returns the number of row affected by the previous statement Both are cleared and reset for each statement executed Store in local variable for later use

RAISERROR Generates an error message (nvarchar(2047)) Can retrieve a custom message from sys.messages Can build a message dynamically Can use substitution parameters (%s, %d etc.) XACT_ABORT setting has no effect i.e. Batch will continue regardless after a statement-level error WITH LOG option logs error in the Windows Application Log Useful if IT Support are involved With TRY … CATCH (SQL Server ) Severity > = 11 transfers to CATCH block Can re-throw an error in a CATCH block

FORMATMESSAGE() Constructs a message from an existing message in sys.messages Accepts substitution parameters Returns message for further processing Returns nvarchar(2047) Can be used to construct a custom message dynamically using substitution parameters (undocumented?)

DEMO SQL Server 2000 Error handling

SQL Server 2005 Similar to TRY … CATCH in.net (but there’s no FINALLY …) If an error occurs in the TRY block, control is passed to the CATCH block BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH [ { sql_statement | statement_block } ] END CATCH TRY … CATCH

TRY … CATCH cont. TRY…CATCH blocks will not trap: Messages with severity 10 or lower Errors with severity of 20 or higher if the session is stopped Client-interrupt requests or broken client connections Sessions ended by the KILL statement Some errors are not handled in the same scope, but will be caught in the calling scope: Compile errors, such as syntax errors Statement-level recompilation errors, e.g. Deferred Name Resolution exceptions

SQL Server 2005 returns the number of the error. ERROR_NUMBER() returns the severity. ERROR_SEVERITY() returns the error state number. ERROR_STATE() returns the name of the stored procedure or trigger where the error occurred. ERROR_PROCEDURE() returns the line number inside the routine that caused the error. ERROR_LINE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times. ERROR_MESSAGE() Error functions

SQL Server 2012 Raises an exception and causes T-SQL Batch to be ended BOL says it honours XACT_ABORT – seems to behave same way regardless Preceding statement must be terminated by a semi-colon (;) Transfers execution to CATCH block if used in TRY … CATCH Can be used in a CATCH block without parameters Outside CATCH block, must have parameters: Error Number, Message and State Message is nvarchar(2048) Error number is an integer ( ) Can use with FORMATMESSAGE() THROW

DEMO SQL Server 2005 and 2012 Error handling

A SUGGESTED APPROACH

Recommendations Include error handling by default It should be part of your application design In every scope level Use TRY.. CATCH in all but simplest procs Consider custom error-handling stored procs Log to application log where appropriate Logging to DB table (e.g. ETL) Will be rolled back if within a transaction Could use Service Broker

DEMO Proposed Approach

QUESTIONS?