Mir*_*ana 2 sql-server locking
我花了两天的大部分时间试图弄清楚我的一张桌子中到底锁定了什么,以及为什么我会陷入从表面上看毫无意义的僵局。
我发现许多博客解释了如何使用未记录的 %%lockres%% 函数来获取表中特定行的哈希值。但是这些指南中的每一个都仅给出了有问题的锁位于表的主键上的示例。我有一个奇怪的情况,主键和唯一键都有锁。
对于上下文:我的主键是 UUID 字符串上的聚集索引。此表中唯一的其他索引是两列(不包括 pk)上的复合唯一键。当我对该表执行INSERT 操作时,我可以看到该表sys.dm_tran_locks
上有两个X
KEY 锁:一个用于 pk,另一个用于唯一约束。
我的死锁报告似乎暗示(除非我读错了——你可以在这里看到我的另一个问题)死锁是由第二个查询引起的,也锁定了唯一索引。
我一直在使用相同的模式在不同的数据库上进行试验,试图找出如何确定死锁的原因是否可以避免。我在一个打开的事务中做了一个 INSERT 并将资源描述与锁定表中所有记录的 %%lockres%% 进行比较,才发现主键上的锁映射到我添加的行,但是锁在唯一索引上根本不匹配表中的任何内容。
这里有人知道这个唯一索引的 %%lockres%% 是什么吗?它显然不是我表中的特定记录。
对于上下文,这是我运行以查看此信息的查询:
此查询列出了我当前数据库上的锁。下面输出。
SELECT dm_tran_locks.request_session_id,
dm_tran_locks.resource_database_id,
CASE
WHEN resource_type = 'object'
THEN OBJECT_NAME(dm_tran_locks.resource_associated_entity_id)
ELSE OBJECT_NAME(partitions.OBJECT_ID)
END AS ObjectName,
partitions.index_id,
indexes.name AS index_name,
dm_tran_locks.resource_type,
dm_tran_locks.resource_description,
dm_tran_locks.resource_associated_entity_id,
dm_tran_locks.request_mode,
dm_tran_locks.request_status,
cleanlockrs
FROM sys.dm_tran_locks
LEFT JOIN sys.partitions ON partitions.hobt_id = dm_tran_locks.resource_associated_entity_id
JOIN sys.indexes ON indexes.OBJECT_ID = partitions.OBJECT_ID AND indexes.index_id = partitions.index_id
CROSS APPLY(
SELECT LEFT(SUBSTRING(resource_description, 2, LEN(resource_description)), LEN(resource_description) - 2)
) clean(cleanlockrs)
WHERE resource_associated_entity_id > 0
AND resource_database_id = DB_ID()
and resource_type = 'KEY'
ORDER BY request_session_id, resource_associated_entity_id
Run Code Online (Sandbox Code Playgroud)
当我然后执行以下查询时,我只返回第一个索引的资源描述的结果。
-- This returns the row I just added.
select * from entities where %%lockres%% like '%27f49aa9c0ac%'
-- This does not return anything.
select * from entities where %%lockres%% like '%7e24236fccb8%'
Run Code Online (Sandbox Code Playgroud)
要在特定索引上查找储物柜,您必须在该索引上显式使用 seek:
select *
from entities WITH (index(unique_entities))
where %%lockres%% like '%7e24236fccb8%'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
186 次 |
最近记录: |