Skip to content

Commit ffb813b

Browse files
BrentOzarclaude
andcommitted
sp_BlitzCache: reuse #plan_cache_by_db for NumberOfPlans aggregation
The UPDATE that sets NumberOfPlans / NumberOfDistinctPlans / plan_multiple_plans was rescanning sys.dm_exec_query_stats + sys.dm_exec_plan_attributes, even though #plan_cache_by_db already holds database_id, query_hash, and query_plan_hash from the earlier scan. Aggregate out of the temp table instead and save a second full pass over the plan cache (and a plan_attributes call per plan_handle) on every default call. Fixes BrentOzarULTD#3939. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 4d0c812 commit ffb813b

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

sp_BlitzCache.sql

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3155,27 +3155,29 @@ OPTION (RECOMPILE) ;
31553155

31563156
-- high level plan stuff
31573157
RAISERROR(N'Gathering high level plan information', 0, 1) WITH NOWAIT;
3158+
/* Aggregate out of #plan_cache_by_db instead of rescanning sys.dm_exec_query_stats
3159+
+ sys.dm_exec_plan_attributes. That temp table was already populated from those
3160+
DMVs above and has everything we need (database_id, query_hash, query_plan_hash),
3161+
so we save a second full pass over the plan cache. */
31583162
UPDATE ##BlitzCacheProcs
31593163
SET NumberOfDistinctPlans = distinct_plan_count,
31603164
NumberOfPlans = number_of_plans ,
31613165
plan_multiple_plans = CASE WHEN distinct_plan_count < number_of_plans THEN number_of_plans END
31623166
FROM
31633167
(
3164-
SELECT
3165-
DatabaseName =
3166-
DB_NAME(CONVERT(int, pa.value)),
3167-
QueryHash =
3168-
qs.query_hash,
3168+
SELECT
3169+
DatabaseName =
3170+
DB_NAME(pc.database_id),
3171+
QueryHash =
3172+
pc.query_hash,
31693173
number_of_plans =
3170-
COUNT_BIG(qs.query_plan_hash),
3171-
distinct_plan_count =
3172-
COUNT_BIG(DISTINCT qs.query_plan_hash)
3173-
FROM sys.dm_exec_query_stats AS qs
3174-
CROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) pa
3175-
WHERE pa.attribute = 'dbid'
3176-
GROUP BY
3177-
DB_NAME(CONVERT(int, pa.value)),
3178-
qs.query_hash
3174+
COUNT_BIG(pc.query_plan_hash),
3175+
distinct_plan_count =
3176+
COUNT_BIG(DISTINCT pc.query_plan_hash)
3177+
FROM #plan_cache_by_db AS pc
3178+
GROUP BY
3179+
DB_NAME(pc.database_id),
3180+
pc.query_hash
31793181
) AS x
31803182
WHERE ##BlitzCacheProcs.QueryHash = x.QueryHash
31813183
AND ##BlitzCacheProcs.DatabaseName = x.DatabaseName

0 commit comments

Comments
 (0)