我尝试对并发线程中的关键部分进行独占读取访问。但是,可序列化隔离级别并不足够,因为在进行更新之前不会发生读取块,而不是在需要避免竞争条件时的初始读取之后下方。
DECLARE @x INT
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
-- need to read-block other threads here
SELECT @x = field1 FROM transtest WHERE id = 1;
SET @x = @x + 1;
UPDATE transtest SET field1 = @x WHERE id = 1;
COMMIT TRANSACTION
除了发布"良性"更新以触发读锁定,如下例所示,是否有更直接的方法来获取它?
UPDATE transtest
SET field1 = (SELECT field1 FROM transtest WHERE id = 1)
WHERE id = 1;
答案 0 :(得分:2)
为什么你不能这样做?
UPDATE transtest SET field1 = field1 + 1 WHERE id = 1;
OP说其他事情正在发生。我想这会做到。
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
-- need to read-block other threads here
SELECT @x = field1 + 1
FROM transtest with (rowlock uplock)
WHERE id = 1;
//other stuff
UPDATE transtest SET field1 = @x WHERE id = 1;
COMMIT TRANSACTION