Skip to content

Commit ed5762e

Browse files
authored
Merge pull request BrentOzarULTD#3940 from BrentOzarULTD/claude/tender-knuth
sp_BlitzCache: reuse #plan_cache_by_db for NumberOfPlans aggregation
2 parents 4d0c812 + 094250d commit ed5762e

1 file changed

Lines changed: 17 additions & 14 deletions

File tree

sp_BlitzCache.sql

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3155,30 +3155,33 @@ 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
3184+
AND ##BlitzCacheProcs.SPID = @@SPID
31823185
OPTION (RECOMPILE) ;
31833186

31843187
-- query level checks

0 commit comments

Comments
 (0)