You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
--One of the common problems with when diagnosing what appears to be a slow scenario where there may be blocking involved is determining what is blocking on SQL Server
--This script works on SQL Server 2008, 2008R2, 2012, 2014, and 2016
--If there is no blocking occurring then this query will return nothing
SELECT*
INTO #runningQueries
FROM master..sysprocesses WITH (NOLOCK);
;WITH BlockingCTE as
(
SELECTq1.blockedas spid
FROM#runningQueries q1
WHEREq1.blocked!=0
ANDq1.blocked not in (SELECT spid FROM#runningQueries q2 WHERE q2.blocked != 0)
)
, recursiveBlocking AS
(
SELECTb.spid, cast(0asSMALLINT) as blocked,
cast(b.spidasvarchar(1000)) as treePath, 0as level,
sp1.sql_handle, b.spidas topBlock
FROM BlockingCTE b
INNER JOIN#runningQueries sp1 on sp1.spid = b.spid
UNION ALL
SELECTsp.spid, rb.spidas blocked,
cast(rb.treePath+'->'+ cast(sp.spidasvarchar(1000)) asVARCHAR(1000)) as treePath,
level +1as level, sp.sql_handle, topBlock
FROM#runningQueries sp
INNER JOIN recursiveBlocking as rb ONrb.spid=sp.blocked
)
, topBlockCount AS
(
SELECT*, count(1) over(partition by topBlock) as NumBlocked
FROM recursiveBlocking
)
SELECT DISTINCT
tb.SPID,
tb.blocked,
tb.treePathas blockingChain,
tb.level,
tb.topBlock,
tb.NumBlocked,
LTRIM(REPLACE(REPLACE(st.text, char(10), ''), char(13), '')) as theQuery
FROM topBlockCount tb
CROSS APPLY sys.dm_exec_sql_text(tb.sql_handle) AS st