Thursday, June 28, 2012

How to deadlock SQL Server?

PROBLEM:
How to deadlock SQL Server?

SOLUTION:
-- step 1: open new query window (window 1) and run only the following 3 lines
begin transaction
update [AdventureWorks].[Person].[Address]
set AddressLine1='aaa' where AddressID=1

-- step 2: open new query window (window 2) and run only the following 5 lines
begin transaction
update [AdventureWorks].[Person].[Address]
set AddressLine1='bbb' where AddressID=2
update [AdventureWorks].[Person].[Address]
set AddressLine1='aaa' where AddressID=1

-- step 3: go back to your first query window (window 1) and run the following 2 line
update [AdventureWorks].[Person].[Address]
set AddressLine1='bbb' where AddressID=2

-- go back to window 2, you will see the following error
Msg 1205, Level 13, State 51, Line 4
Transaction (Process ID 55) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.


More about deadlocking here
How to track down deadlocks using SQL Server Profiler here
And how to detect and ending deadlocks here

If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!

No comments:

Post a Comment