HOLDLOCK with UPDLOCK

前端 未结 3 2244
萌比男神i
萌比男神i 2020-12-31 17:22

It appears using either HOLDLOCK or UPDLOCK in a transaction (say T1), will not block read access from another transaction (say T2).

As I u

3条回答
  •  萌比男神i
    2020-12-31 17:56

    UPDLOCK affects the type of lock. It means for a SELECT statement that U locks will be taken rather than an S lock. At default read committed level they will be released as soon as the data is read.

    The above applies to row and page locks. For table level locks BOL states

    If UPDLOCK is combined with TABLOCK, or a table-level lock is taken for some other reason, an exclusive (X) lock will be taken instead.

    HOLDLOCK means that you get serializable isolation semantics so the locks won't be released until the end of the transaction and at least the whole range covered by your query will be locked to prevent insert of phantoms.

    A U lock is compatible with other S locks but not other U locks (See Lock compatibility matrix) so if the locks were taken out at row or page level this will not block other readers unless they too use the UPDLOCK hint.

    If an object level X lock is taken out due to UPDLOCK however then readers will be blocked trying to acquire an IS lock on the table. In your example query try looking at sys.dm_tran_locks whilst the second query is blocked to see what locks both transactions have / are waiting for.

    For the query in your question

    SELECT *
    FROM   tblTest WITH (UPDLOCK, HOLDLOCK) 
    

    You will always get an X lock on the object if the query plan shows a scan on a heap. If it is an index scan it depends upon the locking granularity used (lock escalation to table level is generally attempted after at least 5,000 lower level locks are taken).

提交回复
热议问题