One way to address this concurrency problem is to include additional criteria in the UPDATE
statement to ensure the requested quantity is still available:
UPDATE dbo.Stock
SET AvailableQuantity -= @OrderQuantity
WHERE
StockID = @StockID
AND AvailableQuantity >= @OrderQuantity;
If no rows are updated, the available quantity needed for this order was depleted by another user. The row count can be checked in the app code after the update (e.g. ExecuteNonQuery()
result) or an error can be raised in T-SQL and caught in the app code to display a message to the user:
UPDATE dbo.Stock
SET AvailableQuantity -= @OrderQuantity
WHERE
StockID = @StockID
AND AvailableQuantity >= @OrderQuantity;
IF @@ROWCOUNT = 0 THROW 50000, 'Insufficient quantity available', 0;