Skip to content

Instantly share code, notes, and snippets.

@brovish
Last active July 21, 2020 22:59
Show Gist options
  • Select an option

  • Save brovish/a234b4e3fcebd76fe9d08d2d787eea0f to your computer and use it in GitHub Desktop.

Select an option

Save brovish/a234b4e3fcebd76fe9d08d2d787eea0f to your computer and use it in GitHub Desktop.
Server-side transaction management
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;
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
@brovish
Copy link
Copy Markdown
Author

brovish commented Jul 14, 2020

from Expert SQL Server Transactions and Locking
APress. ISBN-13: 978-1484239568 ISBN-10: 1484239563
Written by Dmitri V. Korotkevitch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment