SQL Server Deadlock Demo

/* Setup.
*/
use tempdb ;
go
create table dbo.SavingsAccount ( AccountID int not null, Balance money not null ) ;
go
create table dbo.CheckingAccount ( AccountID int not null, Balance money not null ) ;
go
insert into dbo.SavingsAccount ( AccountID, Balance ) values ( 1001, 500.00 ) ;
insert into dbo.CheckingAccount ( AccountID, Balance ) values ( 1001, 100.00 ) ;

/* Code 1.
*/
use tempdb ;
begin transaction ;
update dbo.CheckingAccount 
set Balance = Balance - 100
where AccountID = 1001 ;
waitfor delay '0:00:10' ;
update dbo.SavingsAccount 
set Balance = Balance + 100
where AccountID = 1001 ;
commit ;

/* Code 2.
*/
use tempdb ;
begin transaction ;
update dbo.SavingsAccount 
set Balance = Balance - 100
where AccountID = 1001 ;
update dbo.CheckingAccount 
set Balance = Balance + 100
where AccountID = 1001 ;
commit ;

/* Cleanup.
*/
use tempdb ;
go
if object_id( N'dbo.SavingsAccount', N'u' ) is not null
 drop table dbo.SavingsAccount ;
go
if object_id( N'dbo.CheckingAccount', N'u' ) is not null
 drop table dbo.CheckingAccount ;
go