我正在寻找正确的方法来防止由于多个进程尝试更新表中的同一记录而导致死锁问题。我已经能够通过首先选择记录WITH (UPDLOCK)
然后进行更新来防止死锁。但是,我不确定这是否会一直有效,或者当其他进程插入新记录或更新此表中的其他记录时,它是否会导致其他阻塞问题。
CREATE PROCEDURE usp_ReduceOrderAmount
@OrderId INT,
@ReductionAmount INT
AS
BEGIN
SET NOCOUNT ON
DECLARE @dDateTime AS DATETIME
SET @dDateTime = GETUTCDATE()
BEGIN TRANSACTION
--Quick Fix... Attempt to block other callers who are trying to update the same record.
SELECT * FROM ORDERS WITH (UPDLOCK) WHERE ORDER_ID = @OrderId
UPDATE dbo.ORDERS
SET QTY_OPEN = QTY_OPEN - @ReductionAmount,
UPDATED_WHEN = @dDateTime
WHERE ORDER_ID = @OrderId
COMMIT
END