Question : Cursor Deadlock when moving items from cart to order

I just started testing my web application with real users and as the volume has picked up,  i am receiving the following error once or twice a day.  I am currently running at about 25% volume, so i need a solution.

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

Here is the stored procedure that is causing this issue.  Please help me optimize the cursor / add a no lock / remove cursor all together.

DECLARE @OrderNumber int,
            @Sku char(9),
            @Price decimal(16,2),
            @Qty int

SELECT @OrderNumber = SCOPE_IDENTITY()

DECLARE CartItemsCsr CURSOR FOR      
      
      SELECT Sku, Price, Qty FROM dbo.CartItems WHERE UserID = @UserID
      
      OPEN CartItemsCsr
            FETCH NEXT FROM CartItemsCsr INTO @Sku, @Price, @Qty
            WHILE @@FETCH_STATUS = 0      
            BEGIN
                  
                  INSERT INTO [OrderLine]
                                    ([OrderNumber]
                                 ,[Sku]
                                 ,[Price]
                                 ,[Qty])
                  VALUES
                                 (@OrderNumber
                                 ,@Sku
                                 ,@Price
                                 ,@Qty)      
                                
                  UPDATE Skus SET QtyOnHand = QtyOnHand - @Qty WHERE Sku = @Sku              
                  
            FETCH NEXT FROM CartItemsCsr INTO @Sku, @Price, @Qty      
            END      
      
      CLOSE CartItemsCsr
DEALLOCATE CartItemsCsr      

DELETE CartItems WHERE UserID = @UserID

thanks,

Brian

Answer : Cursor Deadlock when moving items from cart to order

small update
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
DECLARE @OrderNumber int,
            @Sku char(9),
            @Price decimal(16,2),
            @Qty int

SELECT @OrderNumber = SCOPE_IDENTITY()

INSERT INTO [OrderLine]
            ([OrderNumber]
         ,[Sku]
         ,[Price]
         ,[Qty])
SELECT Sku, Price, Qty FROM dbo.CartItems WHERE UserID = @UserID

UPDATE S SET QtyOnHand = QtyOnHand - CI.Qty 
FROM Skus S INNER JOIN dbo.CertItems CI ON S.Sku = CI.Sku
WHERE CI.UserID = @UserID
           
DELETE CartItems WHERE UserID = @UserID
Random Solutions  
 
programming4us programming4us