我已经写了一点 CTE 来获取头阻塞进程的总阻塞时间,我不确定是否应该首先将我希望 CTE 运行的所有进程复制到临时表中,然后对此执行查询- 即我想确保在查询运行时数据不会在我脚下发生变化,并且(最坏的情况),我最终得到一个无限递归循环!
这是我的 SQL,包括临时表——出于性能原因,我宁愿不必使用该表,而是直接转到 CTE 中的 sysprocesses dmv,但我不确定这可能产生的影响。
DECLARE @proc TABLE(
spid SMALLINT PRIMARY KEY,
blocked SMALLINT INDEX blocked_index,
waittime BIGINT)
INSERT INTO @proc
SELECT spid, blocked, waittime
FROM master..sysprocesses
;WITH block_cte AS
(
SELECT spid, CAST(blocked AS BIGINT) [wait_time], spid [root_spid]
FROM @proc
WHERE blocked = 0
UNION ALL
SELECT blocked.spid, blocked.waittime, block_cte.spid
FROM @proc AS blocked
INNER JOIN block_cte ON blocked.blocked = block_cte.spid
)
SELECT root_spid blocking_spid, SUM(wait_time) total_blocking_time
FROM block_cte
GROUP BY root_spid