Last active
July 21, 2020 22:59
-
-
Save brovish/a234b4e3fcebd76fe9d08d2d787eea0f to your computer and use it in GitHub Desktop.
Server-side transaction management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| create proc dbo.MyProc | |
| as | |
| begin | |
| set xact_abort on | |
| begin try | |
| begin tran | |
| /* Some logic here */ | |
| commit | |
| end try | |
| begin catch | |
| if @@TRANCOUNT > 0 -- Transaction is active | |
| rollback; | |
| /* Optional error-handling code */ | |
| throw; | |
| end catch; | |
| end; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DECLARE @retry TINYINT = 5 | |
| -- Keep trying to update table if this task is selected as the deadlock victim. | |
| WHILE (@retry > 0) | |
| BEGIN | |
| BEGIN TRY | |
| BEGIN TRAN | |
| -- some code that can lead to the deadlock | |
| COMMIT | |
| END TRY | |
| BEGIN CATCH | |
| -- Check error number. If deadlock victim error, then reduce retry count | |
| -- for next update retry. If some other error occurred, then exit WHILE loop. | |
| IF (ERROR_NUMBER() = 1205) | |
| SET @retry = @retry - 1; | |
| ELSE | |
| SET @retry = 0; | |
| IF @@trancount > 0 | |
| ROLLBACK; | |
| END CATCH | |
| END |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from Expert SQL Server Transactions and Locking
APress. ISBN-13: 978-1484239568 ISBN-10: 1484239563
Written by Dmitri V. Korotkevitch