模拟死锁的代码

gar*_*rik 27 sql-server deadlock

我正在测试我的应用程序我需要一些稳定的代码来模拟数据库站点上的死锁(如果可能,sql 脚本)。

谢谢你。

添加:

重现只涉及一张表的死锁

Dav*_*all 30

最好的方法是使用您已经拥有的表格。创建两个表 -- table-a, table-b 对于测试,您甚至可以使用相同的信息更新同一列,这样您就不会影响任何真实数据。

例如 UPDATE table_a set ID = ID where ID = 100;

打开同一个数据库的两个会话。一方面,运行

BEGIN TRAN
update table_a set ID=ID where ID = 100;
Run Code Online (Sandbox Code Playgroud)

在两次运行

BEGIN TRAN
update table_b set ID=ID where ID =100;
Run Code Online (Sandbox Code Playgroud)

然后,将更新语句复制到相反的会话并同时运行。一方面,

update table_b set ID=ID where ID =100;
Run Code Online (Sandbox Code Playgroud)

成两半

update table_a set ID=ID where ID = 100;
Run Code Online (Sandbox Code Playgroud)

我现在刚试过这个并开始使用 MS-SQL

Msg 1205, Level 13, State 56, Line 1
Transaction (Process ID 23) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Run Code Online (Sandbox Code Playgroud)


mrd*_*nny 7

使用sp_getapplock系统存储过程获取示例代码上需要的任何锁。

严格来说,这是一个Dijkstra 信号量。不过还是他妈的有用