Professional Documents
Culture Documents
Blocking Sessions
Blocking Sessions
com/2016/12/sql-server-script-to-find-waiting-queries-which-
are-block-by-other-running-queries-find-block-transaction/
===================================================================================
===================================================================================
========================
SELECT N' ' + REPLICATE (N'| ', LEN (LEVEL)/4 - 2) + CASE WHEN (LEN
(LEVEL)/4 - 1) = 0 THEN 'HEAD - ' ELSE '|------ ' END + CAST (SPID AS VARCHAR (10))
+ ' ' +
BATCH AS BLOCKING_TREE , --waittype ,
status, lastwaittype, waittime, Hostname, Loginame, Applicationname, DBname,
Command, CPU, MemUsage, physical_io, LastBatch, GETDATE() as CurrentTime
FROM BLOCKERS with (nolock) ORDER BY LEVEL ASC
===================================================================================
===================================================================================
========================
--DETECT BLOCKING
SELECT wt.session_id,
ot.task_state,
wt.wait_type,
wt.wait_duration_ms,
wt.blocking_session_id,
wt.resource_description,
es.[host_name],
es.[program_name]
FROM sys.dm_os_waiting_tasks wt
INNER JOIN sys.dm_os_tasks ot ON ot.task_address = wt.waiting_task_address
INNER JOIN sys.dm_exec_sessions es ON es.session_id = wt.session_id
WHERE es.is_user_process = 1
-----------------------------------------------------------------------------------
-----------------------
===================================================================================
===================================================================================
========================
Recommendation:
---------------
Use NOLOCK hint in SELECT query to avoid this blocking scenario in future.
- The NOLOCK hint allows SQL to read data from tables by ignoring any locks and
therefore not being blocked by other processes. This can improve query performance,
but also introduces the possibility of dirty reads.
OR