Transaction Simon Cho. Who am I? Simon Cho Blog : Simonsql.com All Presentation and script will be on My.

Slides:



Advertisements
Similar presentations
What is a Transaction? A transaction is a logical logic of work A transaction may have one of two outcomes –When a transaction completes successfully,
Advertisements

FlareCo Ltd ALTER DATABASE AdventureWorks SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS Slide 1.
1 Data Concurrency David Konopnicki 1997 Revised by Mordo Shalom 2004.
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.
Backup and Recovery Part 1.
Transaction log grows unexpectedly
Copyright 2007– WinWare, Inc. Session: How to Utilize the Open Database Architecture of CribMaster Presenter: Phil Stenger.
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.
Managing Transaction and Lock Vu Tuyet Trinh Hanoi University of Technology 1.
A Comedy of Errors Handling Errors in T-SQL Code Andrew Whettam.
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.
Chapter Oracle Server An Oracle Server consists of an Oracle database (stored data, control and log files.) The Server will support SQL to define.
Sofia, Bulgaria | 9-10 October SQL Server 2005 High Availability for developers Vladimir Tchalkov Crossroad Ltd. Vladimir Tchalkov Crossroad Ltd.
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
Architecture Rajesh. Components of Database Engine.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
Oracle Locking Michael Messina Principal Database Analyst Indiana University.
An Oracle server:  Is a database management system that provides an open, comprehensive, integrated approach to information management.  Consists.
Page 1 SQL Server Myths XV ENCONTRO DA COMUNIDADE SQLPORT Rui Ribeiro MCITP 2011/08/16.
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.
1 Chapter 14 DML Tuning. 2 DML Performance Fundamentals DML Performance is affected by: – Efficiency of WHERE clause – Amount of index maintenance – Referential.
MS SQL by: Bryan Bankhead CIS 407. General Concepts  Backing up and Restoring databases and transaction logs is a way that SQL Server provides protection.
1 CS 430 Database Theory Winter 2005 Lecture 16: Inside a DBMS.
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.
By Shanna Epstein IS 257 September 16, Cnet.com Provides information, tools, and advice to help customers decide what to buy and how to get the.
Database structure and space Management. Database Structure An ORACLE database has both a physical and logical structure. By separating physical and logical.
Module 11 Creating Highly Concurrent SQL Server® 2008 R2 Applications.
Transactions and Locks A Quick Reference and Summary BIT 275.
Database structure and space Management. Segments The level of logical database storage above an extent is called a segment. A segment is a set of extents.
1. When things go wrong: how to find SQL error Sveta Smirnova Principle Technical Support Engineer, Oracle.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Stored Procedure Optimization Preventing SP Time Out Delay Deadlocking More DiskReads By: Nix.
Module 11: Managing Transactions and Locks
Relational Database Management System(RDBMS) Structured Query Language(SQL)
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Module 14: Managing Transactions and Locks. Overview Introducing Transactions and Locks Managing Transactions Understanding SQL Server Locking Architecture.
Maciej Pilecki Project Botticelli Ltd. Session Code: DAT402.
Digging Out From Corruption Eddie Wuerch, MCM - Principal, Database Performance - Salesforce Marketing Cloud Data protection and loss recovery with SQL.
6/13/2015 Visit the Sponsor tables to enter their end of day raffles. Turn in your completed Event Evaluation form at the end of the day in the Registration.
# CCNZ What is going on here???
Delete Data Database Administration Fundamentals LESSON 3.4.
BE PREPARED Error Handling & Optimizing T-SQL Code in SQL Server 2000
Transaction Log Fundamentals
Inside transaction logging
Database structure and space Management
11 | Error Handling and Transactions
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
The Nitty-Gritty of Database Backups
PL/SQL Scripting in Oracle:
Advanced PL/SQL Programing
On transactions, and Atomic Operations
Transactions, Locking and Query Optimisation
Inside transaction logging
Turbo-Charged Transaction Logs
TEMPDB – INTERNALS AND USAGE
Transaction Log Fundamentals
On transactions, and Atomic Operations
Transaction Log Internals and Performance David M Maxwell
Objectives Define and describe transactions
Bulk Load and Minimal Logging
Chapter 11 Managing Databases with SQL Server 2000
Accelerated DATABASE RECOVERY
Presentation transcript:

Transaction Simon Cho

Who am I? Simon Cho Blog : Simonsql.com All Presentation and script will be on My blog. This is my first presentation in Public.

Question 1. BEGIN TRAN A INSERT [Tbl] values('A') BEGIN TRAN B INSERT [Tbl] values('B') ROLLBACK TRAN B COMMIT TRAN A Is it working? Obviously Not. Why? Rollback transaction will rollback everything.

Question 2. BEGIN TRAN AAAA INSERT [Tbl] values('A') BEGIN TRAN BBBB INSERT [Tbl] values('B') COMMIT TRAN AAAA COMMIT TRAN BBBB Is it working? No? Answer is Yes. Why? Transaction don’t care the name. Because nested transaction doesn’t support. How? Let’s look at inside transaction log

Question 3 BEGIN TRAN TRUNCATE TABLE [Tbl] ROLLBACK TRAN Is it working? Yes it is. Why? Truncate table is no logging for each row deletion. But, it’s fully logged for system table change. Remember, this is RDBMS. Which mean, all DDL statement can be rollbacked.

Demo - Nested Transaction

Question 4. Which recovery mode is the fastest for this query? Truncate table Table1 GO INSERT INTO Table1 SELECT TOP 'A' FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c CROSS JOIN sys.objects d CROSS JOIN sys.objects e CROSS JOIN sys.objects f A. SIMPLE Recovery mode B. BULK_LOGGED Recovery mode C. FULL Recovery mode Definitely Simple?? Actually all same disregarding recovery mode. Why? The Statement itself required full logged. Hug? Hint : This table doesn’t have any index

Question 4 - Solution Minimal Logging within Simple or Bulk_Logged Mode. – Minimally Logged, No Logging. Truncate table Table1 GO INSERT INTO Table1 SELECT TOP 'A' FROM sys.objects a CROSS JOIN sys.objects b CROSS JOIN sys.objects c CROSS JOIN sys.objects d CROSS JOIN sys.objects e CROSS JOIN sys.objects f A. SIMPLE Recovery mode B. BULK_LOGGED Recovery mode C. FULL Recovery mode How much faster? Vary. Depends on system. In my work station, 400 times less IO 10 times faster WITH(TABLOCK)

Demo – Minimal Logging

What is Recovery Mode? Full – Log backup required – Full logging everything Note : Starting SQL 2008, some statement can be small logged even in full recovery mode. Simple – Automatically reclaims log space. – No log backup Log chain is broken – Not able to restore Point-in-time – Fully Support minimal logging operation Bulk_Logged – Log backup required Note : The log size pretty much same as full recovery mode even the minimal logging operation. – Fully Support minimal logging operation – Log change is NOT broken. – Purpose : Temporary change recovery mode for Minimal logging STMT in Full logging Database. Note – Unfortunately, Mirrored database can’t changed. – When transactional replication is enabled, most of statement fully logged even Bulk Logged mode

3 things for TX error handling 1. – It can determine nested transaction. – It doesn’t know uncommittable transaction. 2. XACT_STATE() – 1 : Commitable active TX. – 0 : No active TX. – -1 : Uncommitable active TX. – It can determine uncommittable transaction. – It doesn’t know nested transaction.

3 things for TX error handling - Cont 3. SET XACT_ABORT – On : In case of run-time error, the entire TX is terminated and rolled back. – Off(Default) : [in some cases only] the Transact- SQL statement that raised the error is rolled back and the transaction continues processing. Note *: Depending upon the severity of the error, the entire transaction may be rolled back even when SET XACT_ABORT is OFF.

Rollback Transaction Rollback Tran – Do NOT print any error message – Rolls back all inner transactions – system function to 0

Question 5. CREATE PROCEDURE varchar(255) OUTPUT AS BEGIN SET NOCOUNT ON; BEGIN TRANSACTION BEGIN TRY SELECT 1/0 -- Bug COMMIT TRANSACTION = 'DONE' END TRY BEGIN CATCH ROLLBACK TRANSACTION = 'FAIL' END CATCH Return 0 END GO

Question 5. - Cont BEGIN TRANSACTION BEGIN TRY VARCHAR(255) EXEC USP_INNER_TRAN OUTPUT SELECT 'InTry' AS WhereWeAre, AS Error, ERROR_MESSAGE() AS ERR_MESSAGE COMMIT TRANSACTION END TRY BEGIN CATCH SELECT 'InCatch' AS WhereWeAre, AS Error, ERROR_MESSAGE() AS ERR_MESSAGE ROLLBACK TRANSACTION END CATCH Is it working?

Question 6 CREATE PROC TestTran AS BEGIN INT SET XACT_ABORT OFF BEGIN TRANSACTION BEGIN TRY SELECT * FROM [TypoNoTable] COMMIT TRAN END TRY BEGIN CATCH = <> 0 BEGIN RAISERROR('Encountered an error, rollback', 16,1) IF <> 0 BEGIN ROLLBACK END RETURN END END CATCH END GO EXEC TestTran Anything wrong this SP?

Demo – Exception Case

Best Practices to Compose SP Goal – Transaction match (Begin and Rollback/Commit) It’s not simple Try catch isn’t perfect. Avoid Nested transaction for easy handling – Error logging for troubleshooting Need to save Enough information in case of error What we need to do? – Define Return code and return it properly – Use Raiserror statement – Transaction Handling – Logging for error message

Best Practices to Compose SP Try Catch isn’t enough for Error Handling Basic Rule – Set XACT_Abort on – Set Nocount on – Define return code SP and check the return code. – Avoid nested transaction Inner SP need to check transaction status first before begin transaction – Transaction should be short enough Execute plan, Minimal Logging – Commit and Rollback transaction at the end. Use Goto statement to handle Commit/Rollback

Best Practices to Compose SP Errors – Expected Error In case of parameter data wrong Return is wrong – UnExpected Error Not expected error – Logical bug – Any Unexpected system error : Server down… Consider Global Error Logging table – Global Database should be online all the time. Consolidated error table Error handling using GoTo statement. – This is old fashion. But, it’s still best I thought.

Demo - Best Practices SP Structure

Bonus – Demo sp_now/sp_now_param

Q & A Welcome for any SQL question. Please feel free to me.

Minimal Logging Operation IndexesRows in tableHintsLogging HeapAnyTABLOCKMinimal HeapAnyNoneFull Heap + IndexAnyTABLOCKFull ClusterEmptyTABLOCK, ORDER (1)Minimal ClusterEmptyNoneFull ClusterAnyNoneFull ClusterAnyTABLOCKFull Cluster + IndexAnyNoneFull Cluster + IndexAnyTABLOCKFull (1) If you are using the INSERT … SELECT method, the ORDER hint does not have to be specified, but the rows must be in the same order as the clustered index. If using BULK INSERT the order hint must be used. (2) Concurrent loads only possible under certain conditions. See “Bulk Loading with the Indexes in Place”. Also, only rows written to newly allocated pages are minimally logged. (3) Depending on the plan chosen by the optimizer, the nonclustered index on the table may either be fully- or minimally logged.

Minimal Logging Reference – Operations That Can Be Minimally Logged – Prerequisites for Minimal Logging in Bulk Import – Minimal logging operation with Traceflag – The Data Loading Performance Guide – Minimal Logging – Considerations for Switching from the Full or Bulk-Logged Recovery Model

Bonus II - Distributed Transaction Distributed Transaction Coordinator(MSDTC) – DCOM service Port 135(TCP) : Listener port Default UDP port range – Netbios UDP port 137 (name services) UDP port 138 (datagram services) TCP port 139 (session services) – SQL port 1433 TCP Statement – Begin distributed transaction – Rollback transaction When – Always happen “begin transaction” between 2 servers such as linked server.

Bonus III - Do not use Savepoint duplicate savepoint names are allowed SavePoint is not a transaction. This is mark on LDF file. We can rollback to SavePoint. Rollback Tran savepoint_name – Does not decrement – Not working in case of Distributed transactions – savepoint name rolls back only to the most recent in case of duplicated name of savepoint – Lock escalations are not released and not converted back previous lock mode. Please do not use it except very special case. It’s NOT a Transaction. Error handling is really painful and debugging is hard. Main problem, in case of error, it can make huge amount of blocking due to lock release issue.