How do you simulate a deadlock for testing purposes

Answer Posted / jay

Below is a quick recipe for a dead lock. Two transactions,
one first updating table 1, then 2 and the other one doing
it in reverse order.

Both transactions wait in the middle for 20 seconds to give
you some time to execute them 'simulaneously'.

When you run the two in transactions in two windows 'at the
same time', you'll only have to wait ~20 seconds, and one of
the windows will experience a dead lock.




CREATE TABLE t1 (i int);
CREATE TABLE t2 (i int);

INSERT t1 SELECT 1;
INSERT t2 SELECT 9;


/* in one window enter: */
BEGIN TRAN
UPDATE t1 SET i = 11 WHERE i = 1
WAITFOR DELAY '00:00:20'
UPDATE t2 SET i = 99 WHERE i = 9
COMMIT

/* in a second window (another transaction) enter: */
BEGIN TRAN
UPDATE t2 SET i = 99 WHERE i = 9
WAITFOR DELAY '00:00:20'
UPDATE t1 SET i = 11 WHERE i = 1
COMMIT

Is This Answer Correct ?    8 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

588


What is difference between drop truncate and delete?

558


What is the difference between index seek vs. Index scan?

583


How to generate create view script on an existing view?

567


What are the differences between char and varchar in ms sql server?

581






What is the meaning of sql server?

534


Can you explain what are various ways to enhance the ssrs report?

585


What is an entity-relationship diagram (erd)?

592


What stored by the msdb? : sql server database administration

563


What does select 1 mean?

535


Explain transaction isolation levels in sql server?

553


What is the use of set nocount on/off statement?

629


What are examples of triggers?

620


What is index in an assignment?

535


What are relationships and mention different types of relationships in the dbms

565