How to deliberately cause a deadlock?

时光总嘲笑我的痴心妄想 提交于 2019-12-30 02:02:31

问题


So I'm trying to track down what looks like a deadlock problem here. I've enabled deadlock logging using DBCC TRACEON(1222,-1) and DBCC TRACEON(1204 ,-1). I'd like to test to make sure the logging catches the deadlock, so how can I cause one to occur in MS SQL 2005? Thanks,


回答1:


Here's some T-SQL to deliberately cause a deadlock.

Object creation:

CREATE TABLE dbo.DeadLockTest (col1 INT)
INSERT dbo.DeadLockTest SELECT 1

CREATE TABLE dbo.DeadLockTest2 (col1 INT)
INSERT dbo.DeadLockTest2 SELECT 1

Open up a new query window and paste this code and execute it:

BEGIN TRAN
UPDATE dbo.DeadLockTest SET col1 = 1

Open up another new query window and paste and execute this code:

BEGIN TRAN
UPDATE dbo.DeadLockTest2 SET col1 = 1
UPDATE dbo.DeadLockTest SET col1 = 1

Go back to your first query window (with the first BEGIN TRAN statement) and execute this code:

UPDATE dbo.DeadLockTest2 SET col1 = 1

Voila! That's a deadlock.




回答2:


This should work:

  • Insert two records, A and B.
  • Open two transactions.
  • Update record A in the first transaction and B in the second transaction.
  • When you know for sure those updates are done:
    • Update record B in the first transaction and A in the second transaction.


来源:https://stackoverflow.com/questions/7813321/how-to-deliberately-cause-a-deadlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!