Home > Database > Mysql Tutorial > body text

SQLServer 中的死锁说明

WBOY
Release: 2016-06-07 18:01:23
Original
1068 people have browsed it

死锁(deadlock)指进程之间互相永久阻塞的状态,SQL可以检测到死锁,并选择终止其中一个事务以干预死锁状态。

两个进程发生死锁的典型例子是:进程T1中获取锁A,申请锁B;进程T2中获取锁B,申请锁A,我们下面动手来演示一下这种情况:

1. 创建一个Database,名为InvDB。

2. 执行下面脚本创建person表并填充两条数据:

3. 在SQL Server Management Studio的两个窗口中同时执行下面的查询:

这段代码在默认的READ COMMITTED隔离级别下运行,两个进程分别在获取一个排它锁的情况下,申请对方的共享锁从而造成死锁。

可见一个进程可以正常更新并显示结果,而另一个进程已经被回滚:

(1 row(s) affected)
Msg 1205, Level 13, State 45, Line 8
Transaction (Process ID 55) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

4. 启动 SQL Server Profiler,选择下面4种Events:

再执行一次上面的死锁实验,可以看到如下所示的死锁图:

非常有趣的一点是:第二次执行上述语句不会发生死锁!这是因为此时两个进程中,SQL Server会智能的识别出update语句是不需要做的,所以都不会去获取排它锁,当然也就不会死锁了。SQL Server 2008 的查询优化器还真是非常强大!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template