Generating Deadlocks in SQL Server


Simulating Deadlock can be achieved by updating 2 tables with a delay in one query window & the reverse update in the second query window as shown below.

Query
Create table TableA(id int,name varchar(50))
Create table TableB(id int,name varchar(50)) Insert into TableA values(1,’krishna’)
Insert into TableB values(2,’krish’)

–Enter in first query window
begin tran
update TableA set name = ‘krish’ where id = 1
waitfor delay ’00:00:30′
update TableB set name = ‘krishna’ where id = 2
commit

–Enter in secondquery window
begin tran
update TableB set name = ‘krishna’ where id = 2
waitfor delay ’00:00:30′
update TableA set name = ‘krish’ where id = 1
commit
You can see the deadlock issue happened in the second query windows as shown below.

(1 row(s) affected)

Server: Msg 1205, Level 13, State 50, Line 1
Transaction (Process ID 52) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: