deadlock because of foreign key?

Posted by George2 on Stack Overflow See other posts from Stack Overflow or by George2
Published on 2010-06-12T16:33:41Z Indexed on 2010/06/12 16:42 UTC
Read the original article Hit count: 350

Hello everyone,

I am using SQL Server 2008 Enterprise. I met with deadlock in the following store procedure, but because of my fault, I did not record the deadlock graph. But now I can not reproduce deadlock issue. I want to have a postmortem to find the root cause of deadlock to avoid deadlock in the future.

The deadlock happens on delete statement. For the delete statement, Param1 is a column of table FooTable, Param1 is a foreign key of another table (refers to another primary key clustered index column of the other table). There is no index on Param1 itself for table FooTable. FooTable has another column which is used as clustered primary key, but not Param1 column.

Here is my guess why there is deadlock, and I want to let people review whether my analysis is correct?

  1. Since Param1 column has no index, there will be a table scan, and will acquire table level lock, because of foreign key, the delete operation will also need to check master table (e.g. to acquire lock on master table);
  2. Some operation on master table acquires master table lock, but want to acquire lock on FooTable;
  3. (1) and (2) cause cycle lock which makes deadlock happen.

My analysis correct? Any reproduce scenario?

create PROCEDURE [dbo].[FooProc]    
(  
 @Param1 int 
 ,@Param2 int  
 ,@Param3 int  
)    
AS    

DELETE FooTable WHERE  Param1 = @Param1     

INSERT INTO FooTable    
 (  
 Param1  
 ,Param2  
 ,Param3  
  )    
 VALUES    
 (  
 @Param1  
 ,@Param2  
 ,@Param3  
  )    

DECLARE @ID bigint    
 SET @ID = ISNULL(@@Identity,-1)    
 IF @ID > 0    
 BEGIN    
      SELECT IdentityStr FROM FooTable WHERE ID = @ID 
 END 

thanks in advance, George

© Stack Overflow or respective owner

Related posts about sql-server-2008

Related posts about stored-procedures