-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_QuickieCache.sql
More file actions
2429 lines (2303 loc) · 85.9 KB
/
sp_QuickieCache.sql
File metadata and controls
2429 lines (2303 loc) · 85.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SET ANSI_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF;
SET STATISTICS TIME, IO OFF;
GO
/*
██████╗ ██╗ ██╗██╗ ██████╗██╗ ██╗██╗███████╗ ██████╗ █████╗ ██████╗██╗ ██╗███████╗
██╔═══██╗██║ ██║██║██╔════╝██║ ██╔╝██║██╔════╝██╔════╝██╔══██╗██╔════╝██║ ██║██╔════╝
██║ ██║██║ ██║██║██║ █████╔╝ ██║█████╗ ██║ ███████║██║ ███████║█████╗
██║▄▄ ██║██║ ██║██║██║ ██╔═██╗ ██║██╔══╝ ██║ ██╔══██║██║ ██╔══██║██╔══╝
╚██████╔╝╚██████╔╝██║╚██████╗██║ ██╗██║███████╗╚██████╗██║ ██║╚██████╗██║ ██║███████╗
╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝
sp_QuickieCache: The plan cache companion to sp_QuickieStore.
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
For usage and licensing details, run:
EXECUTE sp_QuickieCache
@help = 1;
For working through errors:
EXECUTE sp_QuickieCache
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
Uses the Pareto principle to find the vital few queries consuming
disproportionate resources across statements, procedures, functions,
and triggers. Scores across 7 dimensions using PERCENT_RANK and
surfaces queries with impact_score >= @impact_threshold.
Data sources:
* sys.dm_exec_query_stats (statements)
* sys.dm_exec_procedure_stats (stored procedures)
* sys.dm_exec_function_stats (scalar/table-valued functions)
* sys.dm_exec_trigger_stats (triggers)
Requires SQL Server 2016 SP1+ for memory grant and spill columns.
*/
IF OBJECT_ID(N'dbo.sp_QuickieCache', N'P') IS NULL
BEGIN
EXECUTE(N'CREATE PROCEDURE dbo.sp_QuickieCache AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_QuickieCache
(
@top bigint = 10, /*candidates per metric dimension before dedup*/
@sort_order varchar(20) = 'cpu', /*secondary sort after impact_score: cpu, duration, reads, writes, memory, spills, executions*/
@database_name sysname = NULL, /*filter to a specific database*/
@start_date datetime = NULL, /*only include plans created after this date*/
@end_date datetime = NULL, /*only include plans created before this date*/
@minimum_execution_count bigint = 2, /*noise floor for single-exec queries*/
@ignore_system_databases bit = 1, /*exclude master, model, msdb, tempdb*/
@impact_threshold decimal(3, 2) = 0.50, /*minimum impact_score to surface (0.00-1.00)*/
@find_single_use_plans bit = 0, /*show single-use plans consuming the most memory*/
@find_duplicate_plans bit = 0, /*show query hashes with multiple cached plans*/
@debug bit = 0, /*print diagnostics*/
@help bit = 0, /*display parameter help*/
@version varchar(30) = NULL OUTPUT, /*OUTPUT; for support*/
@version_date datetime = NULL OUTPUT /*OUTPUT; for support*/
)
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@version = '1.6',
@version_date = '20260501';
/*
╔══════════════════════════════════════════════════╗
║ Help section ║
╚══════════════════════════════════════════════════╝
*/
IF @help = 1
BEGIN
/*
Introduction
*/
SELECT
introduction =
'hi, i''m sp_QuickieCache!' UNION ALL
SELECT 'you got me from https://code.erikdarling.com' UNION ALL
SELECT 'i analyze the plan cache to find the vital few queries consuming disproportionate resources' UNION ALL
SELECT 'think of me as the plan cache companion to sp_QuickieStore' UNION ALL
SELECT 'i score queries across 7 dimensions using Pareto (80/20) analysis' UNION ALL
SELECT 'from your loving sql server consultant, erik darling: https://erikdarling.com';
/*
Parameters
*/
SELECT
parameter_name =
ap.name,
data_type =
t.name,
description =
CASE ap.name
WHEN N'@top'
THEN N'candidates per metric dimension before dedup'
WHEN N'@sort_order'
THEN N'secondary sort after impact_score'
WHEN N'@database_name'
THEN N'filter to a specific database'
WHEN N'@start_date'
THEN N'only include plans created after this date'
WHEN N'@end_date'
THEN N'only include plans created before this date'
WHEN N'@minimum_execution_count'
THEN N'minimum execution count to include a query'
WHEN N'@ignore_system_databases'
THEN N'exclude system databases (master, model, msdb, tempdb)'
WHEN N'@impact_threshold'
THEN N'minimum impact_score to surface in results'
WHEN N'@find_single_use_plans'
THEN N'show single-use plans consuming the most memory'
WHEN N'@find_duplicate_plans'
THEN N'show query hashes with multiple cached plans'
WHEN N'@debug'
THEN N'print diagnostic information'
WHEN N'@help'
THEN N'how you got here'
WHEN N'@version'
THEN N'OUTPUT; for support'
WHEN N'@version_date'
THEN N'OUTPUT; for support'
ELSE N''
END,
valid_inputs =
CASE ap.name
WHEN N'@top'
THEN N'a positive integer'
WHEN N'@sort_order'
THEN N'cpu, duration, reads, writes, memory, spills, executions'
WHEN N'@database_name'
THEN N'a valid database name'
WHEN N'@start_date'
THEN N'a valid datetime'
WHEN N'@end_date'
THEN N'a valid datetime'
WHEN N'@minimum_execution_count'
THEN N'a positive integer'
WHEN N'@ignore_system_databases'
THEN N'0 or 1'
WHEN N'@impact_threshold'
THEN N'0.00 to 1.00'
WHEN N'@find_single_use_plans'
THEN N'0 or 1'
WHEN N'@find_duplicate_plans'
THEN N'0 or 1'
WHEN N'@debug'
THEN N'0 or 1'
WHEN N'@help'
THEN N'0 or 1'
WHEN N'@version'
THEN N'none; OUTPUT'
WHEN N'@version_date'
THEN N'none; OUTPUT'
ELSE N''
END,
defaults =
CASE ap.name
WHEN N'@top'
THEN N'10'
WHEN N'@sort_order'
THEN N'cpu'
WHEN N'@database_name'
THEN N'NULL'
WHEN N'@start_date'
THEN N'NULL'
WHEN N'@end_date'
THEN N'NULL'
WHEN N'@minimum_execution_count'
THEN N'2'
WHEN N'@ignore_system_databases'
THEN N'1'
WHEN N'@impact_threshold'
THEN N'0.50'
WHEN N'@find_single_use_plans'
THEN N'0'
WHEN N'@find_duplicate_plans'
THEN N'0'
WHEN N'@debug'
THEN N'0'
WHEN N'@help'
THEN N'0'
WHEN N'@version'
THEN N'none; OUTPUT'
WHEN N'@version_date'
THEN N'none; OUTPUT'
ELSE N''
END
FROM sys.all_parameters AS ap
JOIN sys.all_objects AS o
ON ap.object_id = o.object_id
JOIN sys.types AS t
ON ap.system_type_id = t.system_type_id
AND ap.user_type_id = t.user_type_id
WHERE o.name = N'sp_QuickieCache'
ORDER BY
ap.parameter_id
OPTION(MAXDOP 1, RECOMPILE);
/*
License to F5
*/
SELECT
mit_license_yo =
'i am MIT licensed, so like, do whatever'
UNION ALL
SELECT
mit_license_yo =
'see printed messages for full license';
RAISERROR('
MIT License
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
', 0, 1) WITH NOWAIT;
RETURN;
END;
/*
╔══════════════════════════════════════════════════╗
║ Version detection ║
╚══════════════════════════════════════════════════╝
*/
DECLARE
@has_spills bit = 0,
@has_memory_grants bit = 0,
@database_id integer = NULL;
IF EXISTS
(
SELECT
1/0
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_exec_query_stats')
AND ac.name = N'total_spills'
)
BEGIN
SELECT
@has_spills = 1;
END;
IF EXISTS
(
SELECT
1/0
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_exec_query_stats')
AND ac.name = N'min_grant_kb'
)
BEGIN
SELECT
@has_memory_grants = 1;
END;
IF @debug = 1
BEGIN
DECLARE
@debug_msg nvarchar(4000) = N'';
SELECT
@debug_msg =
N'Has spill columns: ' + CONVERT(nvarchar(1), @has_spills) +
N', Has memory grant columns: ' + CONVERT(nvarchar(1), @has_memory_grants);
RAISERROR(N'%s', 0, 1, @debug_msg) WITH NOWAIT;
END;
/*
╔══════════════════════════════════════════════════╗
║ Parameter validation ║
╚══════════════════════════════════════════════════╝
*/
IF @database_name IS NOT NULL
BEGIN
SELECT
@database_id = DB_ID(@database_name);
IF @database_id IS NULL
BEGIN
RAISERROR(N'Database [%s] does not exist on this server.', 16, 1, @database_name) WITH NOWAIT;
RETURN;
END;
END;
IF @impact_threshold < 0.0
OR @impact_threshold > 1.0
BEGIN
RAISERROR(N'@impact_threshold must be between 0.00 and 1.00.', 16, 1) WITH NOWAIT;
RETURN;
END;
IF @top < 1
BEGIN
RAISERROR(N'@top must be at least 1.', 16, 1) WITH NOWAIT;
RETURN;
END;
SELECT
@sort_order = LOWER(LTRIM(RTRIM(@sort_order)));
IF @sort_order NOT IN
(
'cpu', 'duration', 'reads', 'writes',
'memory', 'spills', 'executions'
)
BEGIN
RAISERROR(N'@sort_order must be one of: cpu, duration, reads, writes, memory, spills, executions.', 16, 1) WITH NOWAIT;
RETURN;
END;
/*
╔══════════════════════════════════════════════════╗
║ Single-use plans mode ║
╚══════════════════════════════════════════════════╝
Shows the largest single-use plans by cached size,
sorted by memory consumption descending.
*/
IF @find_single_use_plans = 1
BEGIN
SELECT TOP (@top)
database_name =
DB_NAME(CONVERT(integer, pa.value)),
qs.creation_time,
qs.last_execution_time,
plan_age =
CASE
WHEN DATEDIFF(DAY, qs.creation_time, GETDATE()) > 0
THEN CONVERT(varchar(10), DATEDIFF(DAY, qs.creation_time, GETDATE())) + 'd '
ELSE N''
END +
CONVERT(varchar(10), DATEDIFF(HOUR, qs.creation_time, GETDATE()) % 24) + 'h ' +
CONVERT(varchar(10), DATEDIFF(MINUTE, qs.creation_time, GETDATE()) % 60) + 'm',
time_since_last_execution =
CASE
WHEN DATEDIFF(DAY, qs.last_execution_time, GETDATE()) > 0
THEN CONVERT(varchar(10), DATEDIFF(DAY, qs.last_execution_time, GETDATE())) + 'd '
ELSE N''
END +
CONVERT(varchar(10), DATEDIFF(HOUR, qs.last_execution_time, GETDATE()) % 24) + 'h ' +
CONVERT(varchar(10), DATEDIFF(MINUTE, qs.last_execution_time, GETDATE()) % 60) + 'm',
cached_plan_size_kb =
cp.size_in_bytes / 1024,
clear_plan_command =
N'DBCC FREEPROCCACHE (' +
CONVERT
(
nvarchar(max),
qs.plan_handle,
1
) + N');',
query_text =
st.text,
query_plan =
CASE
WHEN TRY_CAST(qp.query_plan AS xml) IS NOT NULL
THEN TRY_CAST(qp.query_plan AS xml)
WHEN TRY_CAST(qp.query_plan AS xml) IS NULL
THEN
(
SELECT
[processing-instruction(query_plan)] =
N'-- ' + NCHAR(13) + NCHAR(10) +
N'-- This is a huge query plan.' + NCHAR(13) + NCHAR(10) +
N'-- Remove the headers and footers, save it as a .sqlplan file, and re-open it.' + NCHAR(13) + NCHAR(10) +
NCHAR(13) + NCHAR(10) +
REPLACE(qp.query_plan, N'<RelOp', NCHAR(13) + NCHAR(10) + N'<RelOp') +
NCHAR(13) + NCHAR(10) COLLATE Latin1_General_Bin2
FOR
XML
PATH(N''),
TYPE
)
END,
qs.query_hash,
qs.query_plan_hash,
qs.sql_handle,
qs.plan_handle
FROM sys.dm_exec_query_stats AS qs
JOIN sys.dm_exec_cached_plans AS cp
ON cp.plan_handle = qs.plan_handle
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
OUTER APPLY sys.dm_exec_text_query_plan
(
qs.plan_handle,
qs.statement_start_offset,
qs.statement_end_offset
) AS qp
WHERE qs.execution_count = 1
AND (@ignore_system_databases = 0 OR ISNULL(CONVERT(integer, pa.value), 0) NOT IN (1, 2, 3, 4))
AND ISNULL(CONVERT(integer, pa.value), 0) < 32761
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
/* Honor @start_date / @end_date the same as the statement /
procedure / function / trigger paths below — the filters
were documented as applying to all modes, but this
@find_single_use_plans branch silently ignored them before. */
AND (@start_date IS NULL OR qs.creation_time >= @start_date)
AND (@end_date IS NULL OR qs.creation_time < @end_date)
ORDER BY
cp.size_in_bytes DESC
OPTION(RECOMPILE, MAXDOP 1);
RETURN;
END;
/*
╔══════════════════════════════════════════════════╗
║ Duplicate plans mode ║
╚══════════════════════════════════════════════════╝
Shows query hashes that have been compiled into
multiple cached plans, sorted by plan count descending.
*/
IF @find_duplicate_plans = 1
BEGIN
SELECT TOP (@top)
database_name =
DB_NAME(CONVERT(integer, MAX(pa.value))),
qs.query_hash,
plan_count =
FORMAT(COUNT_BIG(DISTINCT qs.plan_handle), N'N0'),
total_executions =
FORMAT(SUM(qs.execution_count), N'N0'),
total_cpu_ms =
FORMAT(SUM(qs.total_worker_time) / 1000.0, N'N3'),
total_duration_ms =
FORMAT(SUM(qs.total_elapsed_time) / 1000.0, N'N3'),
total_logical_reads =
FORMAT(SUM(qs.total_logical_reads), N'N0'),
total_logical_writes =
FORMAT(SUM(qs.total_logical_writes), N'N0'),
total_physical_reads =
FORMAT(SUM(qs.total_physical_reads), N'N0'),
total_rows =
FORMAT(SUM(qs.total_rows), N'N0'),
min_rows =
FORMAT(MIN(qs.min_rows), N'N0'),
max_rows =
FORMAT(MAX(qs.max_rows), N'N0'),
total_cached_size_mb =
FORMAT(SUM(cp.size_in_bytes) / 1048576.0, N'N2'),
oldest_plan =
MIN(qs.creation_time),
newest_plan =
MAX(qs.creation_time),
sample_query_text =
MAX(st.text)
FROM sys.dm_exec_query_stats AS qs
JOIN sys.dm_exec_cached_plans AS cp
ON cp.plan_handle = qs.plan_handle
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE qs.query_hash <> 0x0000000000000000
AND (@ignore_system_databases = 0 OR ISNULL(CONVERT(integer, pa.value), 0) NOT IN (1, 2, 3, 4))
AND ISNULL(CONVERT(integer, pa.value), 0) < 32761
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
GROUP BY
qs.query_hash
HAVING
COUNT_BIG(DISTINCT qs.plan_handle) > 1
ORDER BY
COUNT_BIG(DISTINCT qs.plan_handle) DESC,
SUM(qs.total_worker_time) DESC
OPTION(RECOMPILE, MAXDOP 1);
RETURN;
END;
/*
╔══════════════════════════════════════════════════╗
║ Plan cache health analysis ║
╚══════════════════════════════════════════════════╝
Context-level checks about the overall plan cache state,
independent of individual query analysis.
*/
CREATE TABLE
#plan_cache_health
(
id integer NOT NULL IDENTITY(1, 1),
finding_group nvarchar(100) NOT NULL,
finding nvarchar(200) NOT NULL,
database_name sysname NULL,
priority integer NOT NULL,
details nvarchar(max) NULL
);
/*
Plan creation time distribution:
What % of plans were created in the last 24h / 4h / 1h?
High percentages suggest plan cache instability or memory pressure.
*/
DECLARE
@total_plans bigint = 0,
@plans_24h bigint = 0,
@plans_4h bigint = 0,
@plans_1h bigint = 0,
@pct_24h decimal(5, 2) = 0,
@pct_4h decimal(5, 2) = 0,
@pct_1h decimal(5, 2) = 0,
@oldest_plan_date datetime = NULL;
SELECT
@total_plans = COUNT_BIG(*),
@plans_24h =
SUM
(
CASE
WHEN DATEDIFF(HOUR, qs.creation_time, GETDATE()) <= 24
THEN 1
ELSE 0
END
),
@plans_4h =
SUM
(
CASE
WHEN DATEDIFF(HOUR, qs.creation_time, GETDATE()) <= 4
THEN 1
ELSE 0
END
),
@plans_1h =
SUM
(
CASE
WHEN DATEDIFF(HOUR, qs.creation_time, GETDATE()) <= 1
THEN 1
ELSE 0
END
),
@oldest_plan_date = MIN(qs.creation_time)
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
WHERE 1 = 1
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
OPTION(RECOMPILE);
IF @total_plans > 0
BEGIN
SELECT
@pct_24h = @plans_24h * 100.0 / @total_plans,
@pct_4h = @plans_4h * 100.0 / @total_plans,
@pct_1h = @plans_1h * 100.0 / @total_plans;
END;
IF @pct_24h > 75
BEGIN
INSERT
#plan_cache_health
(
finding_group,
finding,
priority,
details
)
VALUES
(
N'Plan Cache Instability',
N'Most plans are recent',
1,
N'Of ' + FORMAT(@total_plans, N'N0') +
N' cached plans, ' +
CONVERT(nvarchar(10), @pct_24h) + N'% created in the last 24 hours, ' +
CONVERT(nvarchar(10), @pct_4h) + N'% in the last 4 hours, ' +
CONVERT(nvarchar(10), @pct_1h) + N'% in the last 1 hour. ' +
N'This may indicate memory pressure, frequent recompiles, or plan cache flushes. ' +
N'Oldest cached plan: ' + CONVERT(nvarchar(30), @oldest_plan_date, 120) + N'.'
);
END;
ELSE
BEGIN
INSERT
#plan_cache_health
(
finding_group,
finding,
priority,
details
)
VALUES
(
N'Plan Cache Stability',
N'Plan age distribution looks healthy',
254,
N'Of ' + FORMAT(@total_plans, N'N0') +
N' cached plans, ' +
CONVERT(nvarchar(10), @pct_24h) + N'% created in the last 24 hours, ' +
CONVERT(nvarchar(10), @pct_4h) + N'% in the last 4 hours, ' +
CONVERT(nvarchar(10), @pct_1h) + N'% in the last 1 hour. ' +
N'Oldest cached plan: ' + CONVERT(nvarchar(30), @oldest_plan_date, 120) + N'.'
);
END;
/*
Single-use plan bloat per database:
High % of execution_count = 1 plans suggests ad hoc workload
that may benefit from Forced Parameterization.
Only surfaces databases where single-use plans exceed 10%.
*/
INSERT
#plan_cache_health
(
finding_group,
finding,
database_name,
priority,
details
)
SELECT TOP (5)
finding_group =
CASE
WHEN single_use_pct > 75
THEN N'Single-Use Plan Bloat'
ELSE N'Single-Use Plans'
END,
finding =
CASE
WHEN single_use_pct > 75
THEN N'Excessive single-use plans in cache'
ELSE N'Notable single-use plan percentage'
END,
x.database_name,
priority =
CASE
WHEN single_use_pct > 75
THEN 1
ELSE 254
END,
details =
FORMAT(x.single_use_count, N'N0') +
N' of ' + FORMAT(x.total_count, N'N0') +
N' plans (' +
CONVERT(nvarchar(10), x.single_use_pct) +
N'%) executed only once. Consider Forced Parameterization if these are unparameterized ad hoc queries.'
FROM
(
SELECT
database_name =
DB_NAME(CONVERT(integer, pa.value)),
total_count =
COUNT_BIG(*),
single_use_count =
SUM
(
CASE
WHEN qs.execution_count = 1
THEN 1
ELSE 0
END
),
single_use_pct =
CONVERT
(
decimal(5, 2),
SUM
(
CASE
WHEN qs.execution_count = 1
THEN 1
ELSE 0
END
) * 100.0 / COUNT_BIG(*)
)
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
WHERE pa.value IS NOT NULL
AND (@ignore_system_databases = 0 OR CONVERT(integer, pa.value) NOT IN (1, 2, 3, 4))
AND CONVERT(integer, pa.value) < 32761
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
GROUP BY
pa.value
) AS x
WHERE x.single_use_pct > 10
ORDER BY
x.single_use_count DESC
OPTION(RECOMPILE);
/*
Duplicate plan hashes:
Same query_hash compiled into multiple plans suggests
SET option differences or parameterization issues.
*/
DECLARE
@duplicate_hashes bigint = 0,
@duplicate_plans bigint = 0,
@pct_duplicate decimal(5, 2) = 0;
SELECT
@duplicate_hashes = COUNT_BIG(*),
@duplicate_plans = SUM(x.plan_count)
FROM
(
SELECT
plan_count = COUNT_BIG(*)
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
WHERE qs.query_hash <> 0x0000000000000000
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
GROUP BY
qs.query_hash
HAVING
COUNT_BIG(*) > 5
) AS x
OPTION(RECOMPILE);
IF @total_plans > 0
AND @duplicate_plans > 0
BEGIN
SELECT
@pct_duplicate = @duplicate_plans * 100.0 / @total_plans;
END;
IF @pct_duplicate > 5
BEGIN
INSERT
#plan_cache_health
(
finding_group,
finding,
database_name,
priority,
details
)
SELECT TOP (5)
finding_group =
CASE
WHEN @pct_duplicate > 75
THEN N'Severe Plan Duplication'
ELSE N'Plan Duplication'
END,
finding =
CASE
WHEN @pct_duplicate > 75
THEN N'Massive duplicate plan compilation'
ELSE N'Notable duplicate plan compilation'
END,
database_name = DB_NAME(CONVERT(integer, pa.value)),
priority =
CASE
WHEN @pct_duplicate > 75
THEN 1
ELSE 254
END,
details =
FORMAT(COUNT_BIG(DISTINCT qs2.query_hash), N'N0') +
N' query hashes with 5+ plans, totaling ' +
FORMAT(COUNT_BIG(*), N'N0') + N' plans. ' +
N'Most likely unparameterized queries. SET option differences between sessions can also cause this. Consider Forced Parameterization.'
FROM
(
SELECT
qs.query_hash
FROM sys.dm_exec_query_stats AS qs
WHERE qs.query_hash <> 0x0000000000000000
GROUP BY
qs.query_hash
HAVING
COUNT_BIG(*) > 5
) AS x
JOIN sys.dm_exec_query_stats AS qs2
ON qs2.query_hash = x.query_hash
CROSS APPLY
(
SELECT TOP (1)
value = pa.value
FROM sys.dm_exec_plan_attributes(qs2.plan_handle) AS pa
WHERE pa.attribute = N'dbid'
) AS pa
WHERE pa.value IS NOT NULL
AND (@ignore_system_databases = 0 OR CONVERT(integer, pa.value) NOT IN (1, 2, 3, 4))
AND CONVERT(integer, pa.value) < 32761
AND (@database_id IS NULL OR CONVERT(integer, pa.value) = @database_id)
GROUP BY
pa.value
ORDER BY
COUNT_BIG(*) DESC
OPTION(RECOMPILE);
END;
/*
USERSTORE_TOKENPERM memory pressure:
When the token/permission cache consumes >= 10% of buffer pool,
it can starve the plan cache and cause churn.
*/
DECLARE
@buffer_pool_mb decimal(18, 2) = 0,
@tokenperm_mb decimal(18, 2) = 0;
SELECT
@buffer_pool_mb =
SUM
(
CASE
WHEN mc.type = N'MEMORYCLERK_SQLBUFFERPOOL'
THEN mc.pages_kb / 1024.0
ELSE 0
END
),
@tokenperm_mb =
SUM
(
CASE
WHEN mc.type = N'USERSTORE_TOKENPERM'
THEN mc.pages_kb / 1024.0
ELSE 0
END
)
FROM sys.dm_os_memory_clerks AS mc
WHERE mc.type IN (N'MEMORYCLERK_SQLBUFFERPOOL', N'USERSTORE_TOKENPERM')
OPTION(RECOMPILE);
IF @buffer_pool_mb > 0
AND @tokenperm_mb > 2048
AND (@tokenperm_mb / @buffer_pool_mb) * 100.0 >= 10.0
BEGIN
INSERT
#plan_cache_health
(
finding_group,
finding,
priority,
details
)
VALUES
(
N'Memory Pressure',
N'Large USERSTORE_TOKENPERM cache',
10,
N'USERSTORE_TOKENPERM is ' +
FORMAT(CONVERT(bigint, @tokenperm_mb), N'N0') +
N' MB (' +
CONVERT
(
nvarchar(10),
CONVERT(decimal(5, 1), (@tokenperm_mb / @buffer_pool_mb) * 100.0)
) +
N'% of the ' +
FORMAT(CONVERT(bigint, @buffer_pool_mb), N'N0') +
N' MB buffer pool). ' +
N'This can starve the plan cache and cause plan churn. ' +
N'See KB4053569 or consider trace flag 4618/4610.'
);
END;
IF @debug = 1
BEGIN
SELECT
@debug_msg =
N'Plan cache health: ' + CONVERT(nvarchar(20), @total_plans) +
N' total plans, ' + CONVERT(nvarchar(10), @pct_24h) +
N'% < 24h, ' + CONVERT(nvarchar(10), @pct_4h) +
N'% < 4h, ' + CONVERT(nvarchar(10), @pct_1h) + N'% < 1h';
RAISERROR(N'%s', 0, 1, @debug_msg) WITH NOWAIT;
SELECT
@debug_msg =
N'Duplicates: ' + CONVERT(nvarchar(10), @pct_duplicate) + N'%';
RAISERROR(N'%s', 0, 1, @debug_msg) WITH NOWAIT;
SELECT
@debug_msg =
N'TokenPerm: ' + CONVERT(nvarchar(20), @tokenperm_mb) +
N' MB, Buffer pool: ' + CONVERT(nvarchar(20), @buffer_pool_mb) + N' MB';
RAISERROR(N'%s', 0, 1, @debug_msg) WITH NOWAIT;
END;
/*
╔══════════════════════════════════════════════════╗
║ Create staging table ║
╚══════════════════════════════════════════════════╝
All four stat DMVs feed into this single table.
Statements group by query_hash; procedures, functions,
and triggers group by database_id + object_id.
*/
CREATE TABLE
#query_stats
(
id integer NOT NULL IDENTITY(1, 1),
query_type varchar(20) NOT NULL,
database_name sysname NULL,
object_name sysname NULL,
query_hash binary(8) NULL,
plan_count integer NOT NULL DEFAULT 0,
total_executions bigint NOT NULL DEFAULT 0,
total_cpu_ms decimal(38, 2) NOT NULL DEFAULT 0,
total_duration_ms decimal(38, 2) NOT NULL DEFAULT 0,
total_logical_reads bigint NOT NULL DEFAULT 0,
total_logical_writes bigint NOT NULL DEFAULT 0,
total_physical_reads bigint NOT NULL DEFAULT 0,
total_rows bigint NOT NULL DEFAULT 0,
total_grant_mb decimal(38, 2) NOT NULL DEFAULT 0,
total_used_grant_mb decimal(38, 2) NOT NULL DEFAULT 0,
total_spills bigint NOT NULL DEFAULT 0,
max_grant_mb decimal(38, 2) NULL,
max_used_grant_mb decimal(38, 2) NULL,
max_spills bigint NULL,
max_dop integer NULL,
min_rows bigint NULL,
max_rows bigint NULL,
min_cpu_ms decimal(38, 2) NULL,
max_cpu_ms decimal(38, 2) NULL,
min_physical_reads bigint NULL,
max_physical_reads bigint NULL,
min_duration_ms decimal(38, 2) NULL,
max_duration_ms decimal(38, 2) NULL,
oldest_plan_creation datetime NULL,
newest_plan_creation datetime NULL,
last_execution_time datetime NULL,
sample_sql_handle varbinary(64) NULL,
sample_plan_handle varbinary(64) NULL,
sample_statement_start integer NULL,
sample_statement_end integer NULL
);
DECLARE
@sql nvarchar(max) = N'';
/*
╔══════════════════════════════════════════════════╗
║ Step 1a: Collect statement-level stats ║
║ (sys.dm_exec_query_stats, grouped by hash) ║
╚══════════════════════════════════════════════════╝
*/
SELECT
@sql = N'
INSERT
#query_stats
WITH
(TABLOCK)
(
query_type,
database_name,
query_hash,
plan_count,
total_executions,