假设我通过sql显式锁定行,如
BEGIN TRANSACTION
select * from bbajobs WITH (ROWLOCK, UPDLOCK) where JID=40970
然后我怎么能检测到JID为40970的行已被锁定?
我搜索谷歌并找到了一些解决方案,但那些不起作用。请帮我检测一下行是否锁定。感谢。
答案 0 :(得分:2)
也许可以使用像sys.dm_tran_locks这样的系统视图,但是你通常会在页面上找到锁而不是单行,那么如果可行的话,找到特定行是否被锁定将是一件痛苦的事。 / p>
锁模型通常在应用程序中实现(如果您有独立的客户端程序,则在集中式应用程序服务器的内存中管理或在锁定表中管理)
答案 1 :(得分:1)
使用 NOLOCK 和 READPAST 锁定提示。例如。假设您有一个表格,主键名为 Id
SELECT [Id] FROM [dbo].[TableName] WITH(NOLOCK)
WHERE [Id] NOT IN
(
SELECT [Id] FROM [dbo].[TableName] WITH(READPAST)
)
答案 2 :(得分:0)
You can get the list of non-committed transactions with the following query :
SELECT
dm_tran_locks.request_session_id,
dm_tran_locks.resource_database_id,
DB_NAME(dm_tran_locks.resource_database_id) AS dbname,
dm_tran_locks.resource_associated_entity_id,
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
FROM sys.dm_tran_locks
WHERE resource_associated_entity_id > 0
AND resource_database_id = DB_ID();
Then it's possible to get data from the locked row with :
SELECT *
FROM [your_table]
WHERE %%lockres%% = '[insert dm_tran_locks.resource_description value]';
So, you can have the number of locks on your row for your example :
SELECT COUNT(1)
FROM sys.dm_tran_locks locks
INNER JOIN bbajobs
ON bbajobs.%%lockres%% = locks.resource_description
WHERE
resource_associated_entity_id > 0
AND
-- Ensure the lock is on the same database
resource_database_id = DB_ID()
AND
-- Filter on row only
resource_type = 'KEY'
AND
-- Filter on request ID
bbajobs.JID = 40970