我相信马丁已经解释了如何updlock
导致排他锁(+1)......我宁愿将此作为评论/问题发布,但我的评论太大了......
这是updlock
导致x
锁定的快速示例...
IF (OBJECT_ID('tblTest') IS NOT NULL)
DROP TABLE tblTest
CREATE TABLE tblTest (
ID INT NOT NULL
)
BEGIN TRANSACTION
SELECT * FROM dbo.tblTest WITH (UPDLOCK, HOLDLOCK) WHERE ID = 1
SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@SPID
COMMIT
但是,如果您向表中添加聚集索引,则独占表锁将消失,并被RangeS-U
锁替换...
ALTER TABLE dbo.tblTest
ADD CONSTRAINT PK_tblTest
PRIMARY KEY CLUSTERED (ID)
BEGIN TRANSACTION
SELECT * FROM dbo.tblTest WITH (UPDLOCK, HOLDLOCK) WHERE ID = 1
SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@SPID
COMMIT
所以基本上,你在这张表上有一个聚集索引吗?
编辑:
另一个使用非聚集索引的例子......
IF (OBJECT_ID('tblTest') IS NOT NULL)
DROP TABLE tblTest
CREATE TABLE tblTest (
ID INT NOT NULL
)
CREATE NONCLUSTERED INDEX
IX_tblTest ON dbo.tblTest (ID)
BEGIN TRANSACTION
SELECT * FROM dbo.tblTest WITH (HOLDLOCK) WHERE ID = 1
SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@SPID
COMMIT
会导致RangeS-S
锁...
但...
BEGIN TRANSACTION
SELECT * FROM dbo.tblTest WITH (UPDLOCK, HOLDLOCK) WHERE ID = 1
SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@SPID
COMMIT
会导致排他表锁...