今天看到数据库PPT上有个手工模拟死锁的SQL程序:
--用户1:ok
begin transaction t1;
select * from test with (holdlock,xlock) where id=1;
--用户2:OK
begin transaction t2;
select * from test with (holdlock,xlock) where id=2;
--用户1:忙等待
select * from test with (holdlock,xlock) where id=2;
--用户2:死锁构成
select * from test with (holdlock,xlock) where id=1;
其实这个是要分成4个SQL文件去按顺序执行,才能形成死锁:
--SQL1
--用户1:ok
begin transaction t1;
select * from test with (holdlock,xlock) where id=1;
--SQL2
--用户2:OK
begin transaction t2;
select * from test with (holdlock,xlock) where id=2;
以上两个SQL文件都能正常执行并输出结果,但是下面这俩就会有问题了
--SQL3
--用户1:忙等待
select * from test with (holdlock,xlock) where id=2;
SQL3会一直显示执行中
--SQL4
--用户2:死锁构成
select * from test with (holdlock,xlock) where id=1;
SQL4会输出以下错误信息
至此,手动模拟死锁就完成辽