找出 Table 中的哪一行被锁定 - SQL 服务器

Finding out which Row in a Table is locked - SQL server

我有以下查询 return 对特定 table 的任何锁定。但是,我需要它来提供更多信息。我需要知道当前锁定了哪一行。

    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'

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

编辑:以下尝试 -

    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')
);

上面的 return 是我希望它成为 return 的行,但它也会 return table 中的很多旧行,我不会期待它。然而,它似乎接近我所需要的。根据下面答案的建议,我无法让他们到达 return 任何行。我觉得上面的 where 语句是我所缺少的。

adhoc %%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