SQL Server deadlock on read uncommitted isolation level

321 views Asked by At

I get error message "Transaction (Process ID 60) was deadlocked on lock resources with another process ...". I have two simple queries like:

Query 1:

BEGIN try    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN tran  
 
    update RestaurantAccount set CreatedOn = GETDATE()
        where Id = 1
    
    WAITFOR DELAY '00:00:6'
    
    update RestaurantInvoice set CreatedOn = GETDATE()
        where Id = 1
 
commit tran    

END try    
BEGIN catch    

IF(@@TRANCOUNT > 0)    
rollback tran    
 
          SELECT  
             cast(1 as bit) as hasError
            ,ERROR_LINE() AS ErrorLine  
            ,(isnull(ERROR_MESSAGE(),'') + isnull(ERROR_PROCEDURE(),'')) AS ErrorMessage
END catch     

Query 2:

BEGIN try    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN tran  
 
    update RestaurantInvoice set CreatedOn = GETDATE()
        where Id = 1
    
    WAITFOR DELAY '00:00:6'
    
    update RestaurantAccount set CreatedOn = GETDATE()
        where Id = 1

commit tran    

END try    
BEGIN catch    

IF(@@TRANCOUNT > 0)    
rollback tran    

         SELECT  
             cast(1 as bit) as hasError
            ,ERROR_LINE() AS ErrorLine  
            ,(isnull(ERROR_MESSAGE(),'')  ) AS ErrorMessage

END catch  

I set the transaction isolation level to read uncommitted for both, I run the first query, and immediately run the second one, but I still get the deadlock error. As I know, there should be no lock with read uncommitted isolation level. So, what is the reason of deadlock? (I use SQL Server 2014)

1

There are 1 answers

0
SQLpro On

As the name says "READ UNCOMMITTED" apply to READ no writes (INSERT, UPDATE, DELETE, TRUNCATE, MERGE...).

What Thom says is very true. NOLOCK does not mean that a lock will not be put.

And even in READs, under certain circumstances, NOLOCK is ignored, like when there is ENCRYPT or DECRYPT functions used.

And by the ways, READ UNCOMMITTED can give you false positive rows in the results set. Read the paper I wrote (but it is in french)...