Summarize the causes of deadlocks in SQL Server and how to solve them

Source: Internet
Author: User
Tags continue
server| Solution

In fact, the deepest cause of all deadlocks is one: resource competition
Performance One:
A User A accesses table A (lock table a) and then accesses table B
Another User B accesses table B (lock table B), and then attempts to access table A
At this point user a because User B has locked table B, it must wait for User B to release table B, to continue, well, his ladyship will have to wait here.
The same user B will wait for user A to release form A to continue this deadlock.
Workaround:
This deadlock is caused by bugs in your program, and there is no other way to adjust the logic of your program.
Carefully analyze the logic of your program,
1: Try to avoid locking two resources at the same time
2: When two resources must be locked at the same time, ensure that resources are locked in the same order at all times.

Performance Two:
User A reads a record and then modifies the record
This is User B modifying that record
Here in User A's transaction the nature of the lock is raised by a shared lock attempt to the exclusive lock (for update), while the exclusive lock in User B has to wait a-release because A has a shared lock
The shared lock is dropped, and a lock cannot be freed by an exclusive lock that cannot be raised because of the exclusive lock on B, and a deadlock occurs.
This deadlock is more covert, but it often happens in larger projects.
Workaround:
Let user A's transaction (that is, read-write type of operation first), in the Select is the update lock
The syntax is as follows:
SELECT * FROM table1 with (Updlock) where ....




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.