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
4
+
--This script works on SQL Server 2008, 2008R2, 2012, 2014, and 2016
5
+
--If there is no blocking occurring then this query will return nothing
6
+
7
+
SELECT*
8
+
INTO #runningQueries
9
+
FROM master..sysprocesses WITH (NOLOCK);
10
+
11
+
12
+
;WITH BlockingCTE as
13
+
(
14
+
SELECTq1.blockedas spid
15
+
FROM#runningQueries q1
16
+
WHEREq1.blocked!=0
17
+
ANDq1.blocked not in (SELECT spid FROM#runningQueries q2 WHERE q2.blocked != 0)
18
+
)
19
+
, recursiveBlocking AS
20
+
(
21
+
SELECTb.spid, cast(0asSMALLINT) as blocked,
22
+
cast(b.spidasvarchar(1000)) as treePath, 0as level,
23
+
sp1.sql_handle, b.spidas topBlock
24
+
FROM BlockingCTE b
25
+
INNER JOIN#runningQueries sp1 on sp1.spid = b.spid
26
+
27
+
UNION ALL
28
+
29
+
SELECTsp.spid, rb.spidas blocked,
30
+
cast(rb.treePath+'->'+ cast(sp.spidasvarchar(1000)) asVARCHAR(1000)) as treePath,
31
+
level +1as level, sp.sql_handle, topBlock
32
+
FROM#runningQueries sp
33
+
INNER JOIN recursiveBlocking as rb ONrb.spid=sp.blocked
34
+
)
35
+
, topBlockCount AS
36
+
(
37
+
SELECT*, count(1) over(partition by topBlock) as NumBlocked
38
+
FROM recursiveBlocking
39
+
)
40
+
SELECT DISTINCT
41
+
tb.SPID,
42
+
tb.blocked,
43
+
tb.treePathas blockingChain,
44
+
tb.level,
45
+
tb.topBlock,
46
+
tb.NumBlocked,
47
+
LTRIM(REPLACE(REPLACE(st.text, char(10), ''), char(13), '')) as theQuery
48
+
FROM topBlockCount tb
49
+
CROSS APPLY sys.dm_exec_sql_text(tb.sql_handle) AS st
0 commit comments