You are on page 1of 3

-- get the info from requests including the statement

[statement] = SUBSTRING(t.text, (r.statement_start_offset/2) + 1,
case r.statement_end_offset when -1 then datalength(t.text)
else (r.statement_end_offset - r.statement_start_offset)/2
into #row_blocked_sessions
from sys.dm_exec_requests r
cross apply sys.dm_exec_sql_text(sql_handle) t
where status = 'SUSPENDED' and (wait_resource like 'KEY:%' or wait_resourc
e like 'RID:%')

-- get the info on the blocked processes to build the statement

select l.request_session_id, l.resource_associated_entity_id, l.resource_descrip
tion, l.resource_database_id, s.statement
into #blocked_info
from sys.dm_tran_locks l
join #row_blocked_sessions s on l.request_session_id = s.session_id
where l.resource_type in ('RID', 'KEY')

-- begin getting the rows for each statement:

declare crs cursor for select request_session_id, resource_associated_entity_id,
resource_description, resource_database_id, [statement] from #blocked_info

declare @request_session_id int
declare @resource_associated_entity_id bigint
declare @resource_description nvarchar(100)
declare @resource_database_id int
declare @statement nvarchar(max)
declare @exec nvarchar(max)
declare @dbname sysname
declare @schema_name sysname
declare @object_name sysname
declare @index_id int

open crs
fetch next from crs into @request_session_id, @resource_associated_entity_id, @r
esource_description, @resource_database_id, @statement

while @@FETCH_STATUS = 0
-- get the database name:
select @dbname = DB_NAME(@resource_database_id)

select @schema_name = SCHEMA_NAME(o.schema_id), @object_name =, @in
dex_id = p.index_id from sys.partitions p
join sys.objects o on o.object_id = p.object_id
where p.partition_id = @resource_associated_entity_id or p.hobt_id =

-- print the information about the row:
select @request_session_id as session_id, @resource_associated_entity_id a
s resource_associated_entity_id
, @resource_description as resource_description, DB_NAME(@resource_d
atabase_id) as [database]
, '[' + @schema_name + '].[' + @object_name + ']' as [object], @stat
ement as [statement]

-- create the statement to get the row:

set @exec = N'select * from [' + @dbname + N'].[' + @schema_name + N'].['
+ @object_name + N'] with (nolock, index (' + CAST (@index_id as varchar) + N'))
+ N' where %%lockres%% = ''' + @resource_description + N''''
exec sp_executesql @exec

fetch next from crs into @request_session_id, @resource_associated_entity_
id, @resource_description, @resource_database_id, @statement


-- clean up
close crs
deallocate crs
drop table #blocked_info
drop table #row_blocked_sessions