Skip to content

Commit a60effb

Browse files
OleksiiKovalovrwestMSFT
authored andcommitted
Update sql-server-deadlocks-guide.md
adding information about how to handle deadlock error using try/catch block (see https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms179296(v=sql.90)?redirectedfrom=MSDN#working-with-trycatch)
1 parent 1aef901 commit a60effb

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

docs/relational-databases/sql-server-deadlocks-guide.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,50 @@ Because any application submitting [!INCLUDE [tsql](../includes/tsql-md.md)] que
363363
Implementing an error handler that traps error message 1205 allows an application to handle the deadlock situation and take remedial action (for example, automatically resubmitting the query that was involved in the deadlock). By resubmitting the query automatically, the user does not need to know that a deadlock occurred.
364364

365365
The application should pause briefly before resubmitting its query. This gives the other transaction involved in the deadlock a chance to complete and release its locks that formed part of the deadlock cycle. This minimizes the likelihood of the deadlock reoccurring when the resubmitted query requests its locks.
366+
367+
TRY…CATCH can be used to handle deadlocks. The 1205 deadlock victim error can be caught by the CATCH block and the transaction can be rolled back until the threads become unlocked.
368+
369+
```sql
370+
USE AdventureWorks;
371+
GO
372+
-- Declare and set the variable to track the number of retries to try before exiting.
373+
DECLARE @retry INT;
374+
SET @retry = 5;
375+
-- Keep trying to update the table if this task is selected as the deadlock victim.
376+
WHILE (@retry > 0)
377+
BEGIN
378+
BEGIN TRY
379+
BEGIN TRANSACTION;
380+
381+
UPDATE my_sales
382+
SET sales = sales + 1
383+
WHERE itemid = 1;
384+
WAITFOR DELAY '00:00:13';
385+
386+
UPDATE my_sales
387+
SET sales = sales + 1
388+
WHERE itemid = 2;
389+
SET @retry = 0;
390+
COMMIT TRANSACTION;
391+
END TRY
392+
BEGIN CATCH
393+
-- Check the error number.
394+
-- If deadlock victim error, then reduce the retry count for the next update retry.
395+
-- If some other error occurred, then exit
396+
-- retry WHILE loop.
397+
IF (ERROR_NUMBER() = 1205)
398+
SET @retry = @retry - 1;
399+
ELSE
400+
SET @retry = -1;
401+
-- Print error information.
402+
EXECUTE usp_MyErrorLog;
403+
404+
IF XACT_STATE() <> 0
405+
ROLLBACK TRANSACTION;
406+
END CATCH;
407+
END; -- End WHILE loop.
408+
GO
409+
```
366410

367411
## Minimize deadlocks
368412

0 commit comments

Comments
 (0)