UPDLOCK 何时在 SQL 服务器中释放?

When UPDLOCK get released in SQL server?

最近我在 SQL 服务器上完成了提示和锁定。虽然 google 关于这个主题,但我已经阅读了一个博客,其中写了一些我无法理解的查询。这是

BOL 状态:在读取 table 时使用更新锁而不是共享锁,并持有锁直到语句或事务结束。我在翻译这个时遇到了一些麻烦。这是否意味着更新锁在SELECT语句执行后被释放,除非SELECT语句在一个事务中?

换句话说,我在以下两种情况下的假设是否正确?

场景一:无交易

SELECT something FROM table WITH (UPDLOCK)

/* update locks released */

场景二:有交易

BEGIN TRANSACTION 
SELECT something FROM table WITH (UPDLOCK)

/* some code, including an UPDATE */
COMMIT TRANSACTION

/* update locks released */

场景 2 的示例(参考 Whosebug 博客)

BEGIN TRAN

SELECT Id FROM Table1 WITH (UPDLOCK)
WHERE AlertDate IS NULL;

UPDATE Table1 SET AlertDate = getutcdate() 
WHERE AlertDate IS NULL;

COMMIT TRAN 

请帮助理解上述查询。

我的第二个问题是:一旦select语句的执行同时完成UPDLOCK是否被释放?

您在场景 2 中的假设是正确的。

回答你的第二个问题,没有。更新锁一直保留在选定的行上,直到事务结束,或者直到更新语句修改这些行时转换为独占锁。使用 SSMS 一次单步执行每条语句以进行验证。

BEGIN TRAN
    -- execute sp_lock in second session - no locks yet
    SELECT Id FROM Table1 WITH (UPDLOCK) WHERE AlertDate IS NULL;
    -- execute sp_lock in second session - update locks present
    UPDATE Table1 SET AlertDate = getutcdate() WHERE AlertDate IS NULL;
    -- execute sp_lock in second session - update (U) locks are replace by exclusive locks (X) for all row(s) returned by SELECT and modified by the UPDATE (Lock Conversion).
    -- Update locks (U) continue to be held for any row(s) returned by the SELECT but not modified by the UPDATE
    -- exclusive locks (X) are also held on all rows not returned by SELECT but modified by UPDATE. Internally, lock conversion still occurs, because UPDATE statements must read and write.
COMMIT TRAN 

    -- sp_lock in second session - all locks gone.

至于场景1中发生的事情,所有T-SQL语句都存在于隐式或显式事务中。 Senario 1 是隐含的:

BEGIN TRAN
     SELECT something FROM table WITH (UPDLOCK)
     -- execute sp_lock in second session - update locks (U) will be present
     COMMIT TRAN;
     -- execute sp_lock in second session - update locks are gone.

Does this mean that the update locks are released after the execution of the SELECT statement, unless the SELECT statement in within a transaction?

读取该行后将立即释放锁..但锁持有将是 U 锁,因此任何试图修改它的并行事务都必须等待

如果在事务中绕行到select以上,只有在事务提交时才会释放锁,所以任何并行事务获取与U锁不兼容的锁都必须等待

begin tran
select * from t1 with (updlock)

对于下面的第二种情况

BEGIN TRANSACTION 
SELECT something FROM table WITH (UPDLOCK)

/* some code, including an UPDATE */
COMMIT TRANSACTION

想象一下,如果您的 select 查询返回 100 行,所有将使用 U 锁并想象同一事务中的更新影响 2 行,这两行将被转换为 x 锁。所以现在您的查询将有 98 个 u 锁和 2 个 x 锁,直到事务被提交

我认为Updlock是可重复读,可以添加任何新行,但任何并行事务都不能删除或更新现有行