Questions and Answers

What is a deadlock?

A deadlock, also known as a deadly embrace or fatal embrace, occurs when two tasks each own a resource the other needs, and each is waiting for the other to free the resource before proceeding. For example:

Task A locks Object X.
Task B locks Object Y.
Task A requests a lock on Object Y, locked by Task B.
Task B requests a lock on Object X, locked by Task A.

Task A is now waiting on Task B to free Object Y, but Task B will not do that until Task A frees its lock on Object X. If the two tasks were allowed to wait for each other, they would wait forever. If SQL Server detects a deadlock, it chooses one of the tasks as a victim and stops it with an error. This frees the resource locked by the victim task, allowing the other task to complete.

What should a task do when it is chosen as the deadlock victim?

When SQL Server chooses a task as a victim, it rolls back the tasks current transaction and returns a 1205 error:

Your server command (process id nn) was deadlocked with another process and has been chosen as deadlock victim. Rerun your command.

Usually, tasks getting this error should simply rerun their transaction. By the time their SQL commands are sent back to the server, the other task should have completed its transaction and freed all the locks it held.

If an application experiences high numbers of deadlocks, it it is most likely due to coding such as that shown in the combination of the xfer_to_savings and xfer_to_checking_1 procedures. You should investigate, and change the application logic to the sequence illustrated by the combination of the xfer_to_savings and xfer_to_checking_-2 procedures.