I'm reading Understanding Locking in SQL Server. But I don't quite understand the purpose of update locks.
Details description as below:
Update Locks
Update (U) locks prevent a common form of deadlock. A typical update pattern consists of a transaction reading a record, acquiring a shared (S) lock on the resource (page or row), and then modifying the row, which requires lock conversion to an exclusive (X) lock. If two transactions acquire shared-mode locks on a resource and then attempt to update data concurrently, one transaction attempts the lock conversion to an exclusive (X) lock. The shared-mode-to-exclusive lock conversion must wait because the exclusive lock for one transaction is not compatible with the shared-mode lock of the other transaction; a lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock for its update. Because both transactions are converting to exclusive (X) locks, and they are each waiting for the other transaction to release its shared-mode lock, a deadlock occurs.
To avoid this potential deadlock problem, update (U) locks are used. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock. Otherwise, the lock is converted to a shared-mode lock.
Consider below two transaction(both transaction execute at Isolation Level Repeatable Read in order to hold S lock during transaction):
execute below SQL in TRAN1.
BEGIN TRAN
SELECT BrandName FROM dbo.Brand WHERE BrandId=2
now, TRAN1 grant S lock for RID
execute below SQL in TRAN2
BEGIN TRAN
SELECT BrandName FROM dbo.Brand WHERE BrandId=2
now, TRAN2 grant S lock for same RID resource as TRAN1
execute below SQL in TRAN1
UPDATE dbo.Brand SET BrandName='YBrand' WHERE BrandId=2
now, TRAN1 S lock convert to U lock and the U lock wait TRAN2 S lock release to convert to X lock
execute below SQL in TRAN2
UPDATE dbo.Brand SET BrandName='ZBrand' WHERE BrandId=2
Then deadlock occurs.
Up deadlock is exactly as description as what U lock use for prevent. But deadlock still occurs.
So my question is: what U lock different with X lock? And which situation make it can prevent deadlock instead of use X lock?
selectstatements in both transactions to includewith (updlock). - GSerg