查找表中的哪一行被锁定-SQL Server

时间:2020-04-07 13:14:43

标签: sql sql-server locking

我有以下查询,该查询返回特定表上的所有锁。但是,我需要它来提供更多信息。我需要知道当前正在锁定的行。

    SELECT 
 DB_NAME(resource_database_id)
 , s.original_login_name
 , s.status
 , s.program_name
 , s.host_name
 ,*
from 
 sys.dm_tran_locks dbl
  JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
where 
  resource_associated_entity_id = object_id('dbname.scheme.table')AND  DB_NAME(resource_database_id) = 'dbname'

此查询用于显示何时有锁。我只需要更多信息。例如,我要查看的表包含很多订单。如果有人坐在应用程序中的那些命令之一中。该行将被锁定,我需要查询以显示被锁定行的顺序号。

编辑:尝试以下-

    select *
from db.scheme.table
where %%lockres%% in
(
select l.resource_description
from sys.dm_tran_locks as l
where l.resource_type in ('RID')
);

上面的代码返回了我期望它返回的行,但是它也将返回我不希望它返回的表中的许多旧行。但是,它似乎接近我的需求。根据下面答案的建议,我无法让他们返回任何行。我感觉上面缺少的是where语句。

1 个答案:

答案 0 :(得分:1)

临时%% lockres %%行级锁定(不适用于持续监视等)

set transaction isolation level read uncommitted;

select *
from dbX.schemaY.tableZ 
where %%lockres%% in 
(
    select l.resource_description
    from sys.dm_tran_locks as l
    join sys.partitions as p on l.resource_associated_entity_id = p.partition_id
    where l.resource_type in ('KEY', 'RID')
    and p.object_id = object_id('dbX.schemaY.tableZ')
);

--demo
use tempdb
go

create table dbo.testtableX
(
    id int constraint pkclusteredid primary key clustered,
    thename nvarchar(128)
);
go

insert into dbo.testtableX(id, thename)
select object_id, name
from sys.objects
go

--select *
--from  dbo.testtableX;

--lock some rows
begin transaction
update dbo.testtableX with(rowlock)
set thename = thename+'update'
where id in (44, 45, 46)

--..or in another ssms windows
select 'locked rows', *
from dbo.testtableX with(nolock)
where %%lockres%% in
(
select l.resource_description
from sys.dm_tran_locks as l
where l.resource_type in ('KEY', 'RID') --index lock, KEY
);

select l.resource_description, *
from sys.dm_tran_locks as l
where l.resource_type in ('KEY', 'RID') --index lock, KEY

rollback transaction
go

--to heap
alter table dbo.testtableX drop constraint pkclusteredid;

--...repeat
begin transaction
update dbo.testtableX with(rowlock)
set thename = thename+'update'
where id in (54, 55, 56)

--..or in another ssms windows
select 'locked rows', *
from dbo.testtableX with(nolock)
where %%lockres%% in
(
select l.resource_description
from sys.dm_tran_locks as l
where l.resource_type in ('KEY', 'RID') --row identifier lock, RID
);

select l.resource_description, *
from sys.dm_tran_locks as l
where l.resource_type in ('KEY', 'RID') --RID

rollback transaction
go

drop table dbo.testtableX;
go
相关问题