Transaction (Process ID) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction

前端 未结 5 1910
耶瑟儿~
耶瑟儿~ 2020-12-30 00:47

I have a C# application which is inserting data into SQL Server (2008) table using stored procedure. I am using multi-threading to do this. The stored procedure is being cal

5条回答
  •  [愿得一人]
    2020-12-30 01:27

    You can encapsulate your query in a TRY CATCH block, and catching error numbers (related to locks)

    1. 1204
    2. 1205
    3. 1222

    Then you can automate retries, up to a certain number.. So you would do something like the following;

             DECLARE @RetryNo Int = 1
         ,@RetryMaxNo Int = 5;
       WHILE @RetryNo < @RetryMaxNo
          BEGIN
             BEGIN TRY 
    
             -- put your query that generates locks here....
    
                SELECT   @RetryNo = @RetryMaxNo;
             END TRY
             BEGIN CATCH
                IF ERROR_NUMBER() IN (1204, 1205, 1222)
                   BEGIN
                      SET @RetryNo += 1;
                      -- it will wait for 10 seconds to do another attempt
                      WAITFOR DELAY '00:00:10';
                   END 
                ELSE
                   THROW;
             END CATCH
          END 
    

    You can also use table hints such as UPDLOCK.

提交回复
热议问题