27
Transaction Simon Cho

Transaction

  • Upload
    lew

  • View
    24

  • Download
    0

Embed Size (px)

DESCRIPTION

Transaction. Simon Cho. Who am I?. Simon Cho Blog : Simonsql.com Email : [email protected] 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 - PowerPoint PPT Presentation

Citation preview

Page 1: Transaction

Transaction

Simon Cho

Page 2: Transaction

Who am I?

• Simon Cho• Blog : Simonsql.com• Email : [email protected]

• All Presentation and script will be on My blog.• This is my first presentation in Public.

Page 3: Transaction

Question 1.

BEGIN TRAN AINSERT [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.

Page 4: Transaction

Question 2.

BEGIN TRAN AAAAINSERT [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 th

e name.

Because nested tra

nsaction doesn’t support.

How? Let’s look at in

side tra

nsaction log

Page 5: Transaction

Question 3

BEGIN TRANTRUNCATE TABLE [Tbl]

ROLLBACK TRAN

• Is it working?

Yes it is.

Why? Truncate table is no logging fo

r each

row deletion. But, it’s

fully logged for sy

stem

table change.

Remember, this i

s RDBMS. W

hich mean, all

DDL statement ca

n be rollbacked.

Page 6: Transaction

Demo - Nested Transaction

Page 7: Transaction

Question 4.

• Which recovery mode is the fastest for this query?Truncate table Table1 GO

INSERT INTO Table1SELECT TOP 1000000 '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 modeB. BULK_LOGGED Recovery modeC. FULL Recovery mode

Definitely Sim

ple??

Actually all s

ame disregarding

recovery mode.

Why? The Statement itself r

equired

full logged.

Hug?

Hint : This table doesn’t have any index

Page 8: Transaction

Question 4 - Solution• Minimal Logging within Simple or Bulk_Logged Mode.

– Minimally Logged, No Logging.

Truncate table Table1 GO

INSERT INTO Table1SELECT TOP 1000000 '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 modeB. BULK_LOGGED Recovery modeC. FULL Recovery mode

How much faster?

Vary. Depends o

n syste

m.

In my work station,

400 times less I

O

10 times faste

r

WITH(TABLOCK)

Page 9: Transaction

Demo – Minimal Logging

Page 10: Transaction

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

Page 11: Transaction

3 things for TX error handling

• 1. @@TranCount– 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.

Page 12: 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.

Page 13: Transaction

Rollback Transaction

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

Page 14: Transaction

Question 5.CREATE PROCEDURE USP_INNER_TRAN@output varchar(255) OUTPUTASBEGINSET NOCOUNT ON; BEGIN TRANSACTION

BEGIN TRY SELECT 1/0 -- Bug COMMIT TRANSACTION

SELECT @output = 'DONE' END TRY BEGIN CATCH ROLLBACK TRANSACTION SELECT @output = 'FAIL' END CATCH

Return 0ENDGO

Page 15: Transaction

Question 5. - Cont

BEGIN TRANSACTION BEGIN TRY DECLARE @output VARCHAR(255) EXEC USP_INNER_TRAN @output=@output OUTPUT

SELECT 'InTry' AS WhereWeAre , @@TRANCOUNT , @@ERROR AS Error , ERROR_MESSAGE() AS ERR_MESSAGE COMMIT TRANSACTIONEND TRYBEGIN CATCH SELECT 'InCatch' AS WhereWeAre , @@TRANCOUNT , @@ERROR AS Error , ERROR_MESSAGE() AS ERR_MESSAGE ROLLBACK TRANSACTIONEND CATCH

• Is it working?

Page 16: Transaction

Question 6CREATE PROC TestTranASBEGIN DECLARE @Err INT SET XACT_ABORT OFF BEGIN TRANSACTION BEGIN TRY SELECT * FROM [TypoNoTable] COMMIT TRAN END TRY BEGIN CATCH SET @ERR = @@ERROR IF @Err <> 0 BEGIN RAISERROR('Encountered an error, rollback', 16,1) IF @@TRANCOUNT <> 0 BEGIN ROLLBACK END RETURN (@ERR) END END CATCHENDGO

EXEC TestTran

• Anything wrong this SP?

Page 17: Transaction

Demo – Exception Case

Page 18: Transaction

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

Page 19: Transaction

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

Page 20: Transaction

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.

Page 21: Transaction

Demo - Best Practices SP Structure

Page 22: Transaction

Bonus – Demo

sp_now/sp_now_param

Page 23: Transaction

Q & A

[email protected]

Welcome for any SQL question.Please feel free to email me.

Page 24: Transaction

Minimal Logging OperationIndexes Rows in table Hints LoggingHeap Any TABLOCK Minimal

Heap Any None Full

Heap + Index Any TABLOCK Full

Cluster Empty TABLOCK, ORDER (1) Minimal

Cluster Empty None Full

Cluster Any None Full

Cluster Any TABLOCK Full

Cluster + Index Any None Full

Cluster + Index Any TABLOCK Full

http://technet.microsoft.com/en-us/library/dd425070%28v=sql.100%29.aspx(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.

Page 25: Transaction

Minimal Logging Reference• Minimal Logging Reference

– Operations That Can Be Minimally Logged• http://technet.microsoft.com/en-us/library/ms191244(v=sql.100).aspx

– Prerequisites for Minimal Logging in Bulk Import• http://technet.microsoft.com/en-us/library/ms190422%28v=sql.100%29.aspx

– Minimal logging operation with Traceflag 610• http://simonsql.com/2011/12/05/minimal-logging-operation-with-traceflag-610/

– The Data Loading Performance Guide• http://msdn.microsoft.com/en-us/library/dd425070.aspx

– Minimal Logging• http://www.sqlservercentral.com/articles/Administration/100856/

– Considerations for Switching from the Full or Bulk-Logged Recovery Model• http://technet.microsoft.com/en-us/library/ms190203(v=sql.105).aspx

Page 26: Transaction

Bonus II - Distributed Transaction• Distributed Transaction Coordinator(MSDTC)

– DCOM service• Port 135(TCP) : Listener port• Default UDP port range 1024-5000

– 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.

Page 27: Transaction

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 @@TRANCOUNT– 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.