-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_QuickieStore.sql
More file actions
15853 lines (14797 loc) · 487 KB
/
sp_QuickieStore.sql
File metadata and controls
15853 lines (14797 loc) · 487 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_NULLS ON;
SET ANSI_PADDING ON;
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
/*
██████╗ ██╗ ██╗██╗ ██████╗██╗ ██╗██╗███████╗
██╔═══██╗██║ ██║██║██╔════╝██║ ██╔╝██║██╔════╝
██║ ██║██║ ██║██║██║ █████╔╝ ██║█████╗
██║▄▄ ██║██║ ██║██║██║ ██╔═██╗ ██║██╔══╝
╚██████╔╝╚██████╔╝██║╚██████╗██║ ██╗██║███████╗
╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚══════╝
███████╗████████╗ ██████╗ ██████╗ ███████╗██╗
██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝██║
███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║
╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ╚═╝
███████║ ██║ ╚██████╔╝██║ ██║███████╗██╗
╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
For usage and licensing details, run:
EXECUTE sp_QuickieStore
@help = 1;
For working through errors:
EXECUTE sp_QuickieStore
@debug = 1;
For performance issues:
EXECUTE sp_QuickieStore
@troubleshoot_performance = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID(N'dbo.sp_QuickieStore', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_QuickieStore AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_QuickieStore
(
@database_name sysname = NULL, /*the name of the database you want to look at query store in*/
@sort_order varchar(20) = 'cpu', /*the runtime metric you want to prioritize results by*/
@top bigint = 10, /*the number of queries you want to pull back*/
@start_date datetimeoffset(7) = NULL, /*the begin date of your search, will be converted to UTC internally*/
@end_date datetimeoffset(7) = NULL, /*the end date of your search, will be converted to UTC internally*/
@timezone sysname = NULL, /*user specified time zone to override dates displayed in results*/
@execution_count bigint = NULL, /*the minimum number of executions a query must have*/
@duration_ms bigint = NULL, /*the minimum duration a query must have to show up in results*/
@execution_type_desc nvarchar(60) = NULL, /*the type of execution you want to filter by (regular, aborted, exception)*/
@procedure_schema sysname = NULL, /*the schema of the procedure you're searching for*/
@procedure_name sysname = NULL, /*the name of the programmable object you're searching for*/
@include_plan_ids nvarchar(4000) = NULL, /*a list of plan ids to search for*/
@include_query_ids nvarchar(4000) = NULL, /*a list of query ids to search for*/
@include_query_hashes nvarchar(4000) = NULL, /*a list of query hashes to search for*/
@include_plan_hashes nvarchar(4000) = NULL, /*a list of query plan hashes to search for*/
@include_sql_handles nvarchar(4000) = NULL, /*a list of sql handles to search for*/
@ignore_plan_ids nvarchar(4000) = NULL, /*a list of plan ids to ignore*/
@ignore_query_ids nvarchar(4000) = NULL, /*a list of query ids to ignore*/
@ignore_query_hashes nvarchar(4000) = NULL, /*a list of query hashes to ignore*/
@ignore_plan_hashes nvarchar(4000) = NULL, /*a list of query plan hashes to ignore*/
@ignore_sql_handles nvarchar(4000) = NULL, /*a list of sql handles to ignore*/
@query_text_search nvarchar(4000) = NULL, /*query text to search for*/
@query_text_search_not nvarchar(4000) = NULL, /*query text to exclude*/
@escape_brackets bit = 0, /*Set this bit to 1 to search for query text containing square brackets (common in .NET Entity Framework and other ORM queries)*/
@escape_character nchar(1) = N'\', /*Sets the ESCAPE character for special character searches, defaults to the SQL standard backslash (\) character*/
@only_queries_with_hints bit = 0, /*Set this bit to 1 to retrieve only queries with query hints*/
@only_queries_with_feedback bit = 0, /*Set this bit to 1 to retrieve only queries with query feedback*/
@only_queries_with_variants bit = 0, /*Set this bit to 1 to retrieve only queries with query variants*/
@only_queries_with_forced_plans bit = 0, /*Set this bit to 1 to retrieve only queries with forced plans*/
@only_queries_with_forced_plan_failures bit = 0, /*Set this bit to 1 to retrieve only queries with forced plan failures*/
@wait_filter varchar(20) = NULL, /*wait category to search for; category details are below*/
@query_type varchar(11) = NULL, /*filter for only ad hoc queries or only from queries from modules*/
@expert_mode bit = 0, /*returns additional columns and results*/
@hide_help_table bit = 0, /*hides the "bottom table" that shows help and support information*/
@format_output bit = 1, /*returns numbers formatted with commas and most decimals rounded away*/
@get_all_databases bit = 0, /*looks for query store enabled user databases and returns combined results from all of them*/
@include_databases nvarchar(MAX) = NULL, /*comma-separated list of databases to include (only when @get_all_databases = 1)*/
@exclude_databases nvarchar(MAX) = NULL, /*comma-separated list of databases to exclude (only when @get_all_databases = 1)*/
@workdays bit = 0, /*Use this to filter out weekends and after-hours queries*/
@work_start time(0) = '9am', /*Use this to set a specific start of your work days*/
@work_end time(0) = '5pm', /*Use this to set a specific end of your work days*/
@regression_baseline_start_date datetimeoffset(7) = NULL, /*the begin date of the baseline that you are checking for regressions against (if any), will be converted to UTC internally*/
@regression_baseline_end_date datetimeoffset(7) = NULL, /*the end date of the baseline that you are checking for regressions against (if any), will be converted to UTC internally*/
@regression_comparator varchar(20) = NULL, /*what difference to use ('relative' or 'absolute') when comparing @sort_order's metric for the normal time period with the regression time period.*/
@regression_direction varchar(20) = NULL, /*when comparing against the regression baseline, what do you want the results sorted by ('magnitude', 'improved', or 'regressed')?*/
@include_query_hash_totals bit = 0, /*will add an additional column to final output with total resource usage by query hash, may be skewed by query_hash and query_plan_hash bugs with forced plans/plan guides*/
@include_maintenance bit = 0, /*Set this bit to 1 to add maintenance operations such as index creation to the result set*/
@find_high_impact bit = 0, /*finds the vital few queries consuming disproportionate resources across cpu, duration, reads, writes, memory, and executions*/
@primary_window nvarchar(20) = NULL, /*with @find_high_impact, restricts results to queries whose majority activity is in this window: business, off-hours, or weekend*/
@help bit = 0, /*return available parameter details, etc.*/
@debug bit = 0, /*prints dynamic sql, statement length, parameter and variable values, and raw temp table contents*/
@troubleshoot_performance bit = 0, /*set statistics xml on for queries against views*/
@log_to_table bit = 0, /*enable logging to permanent tables instead of returning results*/
@log_database_name sysname = NULL, /*database to store logging tables*/
@log_schema_name sysname = NULL, /*schema to store logging tables*/
@log_table_name_prefix sysname = N'QuickieStore', /*prefix for all logging table names*/
@log_retention_days integer = 30, /*days of data to retain, 0 = keep indefinitely*/
@version varchar(30) = NULL OUTPUT, /*OUTPUT; for support*/
@version_date datetime = NULL OUTPUT /*OUTPUT; for support*/
)
WITH RECOMPILE
AS
BEGIN
SET STATISTICS XML OFF;
SET NOCOUNT ON;
SET XACT_ABORT OFF;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
BEGIN TRY
/*
These are for your outputs.
*/
SELECT
@version = '6.5',
@version_date = '20260420';
/*
Helpful section! For help.
*/
IF @help = 1
BEGIN
/*
Introduction
*/
SELECT
introduction =
'hi, i''m sp_QuickieStore!' UNION ALL
SELECT 'you got me from https://code.erikdarling.com' UNION ALL
SELECT 'i can be used to quickly grab misbehaving queries from query store' UNION ALL
SELECT 'the plan analysis is up to you; there will not be any XML shredding here' UNION ALL
SELECT 'so what can you do, and how do you do it? read below!' 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'@database_name' THEN 'the name of the database you want to look at query store in'
WHEN N'@sort_order' THEN 'the runtime metric you want to prioritize results by'
WHEN N'@top' THEN 'the number of queries you want to pull back'
WHEN N'@start_date' THEN 'the begin date of your search, will be converted to UTC internally'
WHEN N'@end_date' THEN 'the end date of your search, will be converted to UTC internally'
WHEN N'@timezone' THEN 'user specified time zone to override dates displayed in results'
WHEN N'@execution_count' THEN 'the minimum number of executions a query must have'
WHEN N'@duration_ms' THEN 'the minimum duration a query must have to show up in results'
WHEN N'@execution_type_desc' THEN 'the type of execution you want to filter by (regular, aborted, exception)'
WHEN N'@procedure_schema' THEN 'the schema of the procedure you''re searching for'
WHEN N'@procedure_name' THEN 'the name of the programmable object you''re searching for'
WHEN N'@include_plan_ids' THEN 'a list of plan ids to search for'
WHEN N'@include_query_ids' THEN 'a list of query ids to search for'
WHEN N'@include_query_hashes' THEN 'a list of query hashes to search for'
WHEN N'@include_plan_hashes' THEN 'a list of query plan hashes to search for'
WHEN N'@include_sql_handles' THEN 'a list of sql handles to search for'
WHEN N'@ignore_plan_ids' THEN 'a list of plan ids to ignore'
WHEN N'@ignore_query_ids' THEN 'a list of query ids to ignore'
WHEN N'@ignore_query_hashes' THEN 'a list of query hashes to ignore'
WHEN N'@ignore_plan_hashes' THEN 'a list of query plan hashes to ignore'
WHEN N'@ignore_sql_handles' THEN 'a list of sql handles to ignore'
WHEN N'@query_text_search' THEN 'query text to search for'
WHEN N'@query_text_search_not' THEN 'query text to exclude'
WHEN N'@escape_brackets' THEN 'Set this bit to 1 to search for query text containing square brackets (common in .NET Entity Framework and other ORM queries)'
WHEN N'@escape_character' THEN 'Sets the ESCAPE character for special character searches, defaults to the SQL standard backslash (\) character'
WHEN N'@only_queries_with_hints' THEN 'only return queries with query hints'
WHEN N'@only_queries_with_feedback' THEN 'only return queries with query feedback'
WHEN N'@only_queries_with_variants' THEN 'only return queries with query variants'
WHEN N'@only_queries_with_forced_plans' THEN 'only return queries with forced plans'
WHEN N'@only_queries_with_forced_plan_failures' THEN 'only return queries with forced plan failures'
WHEN N'@wait_filter' THEN 'wait category to search for; category details are below'
WHEN N'@query_type' THEN 'filter for only ad hoc queries or only from queries from modules'
WHEN N'@expert_mode' THEN 'returns additional columns and results'
WHEN N'@hide_help_table' THEN 'hides the "bottom table" that shows help and support information'
WHEN N'@format_output' THEN 'returns numbers formatted with commas and most decimals rounded away'
WHEN N'@get_all_databases' THEN 'looks for query store enabled user databases and returns combined results from all of them'
WHEN N'@include_databases' THEN 'comma-separated list of databases to include (only when @get_all_databases = 1)'
WHEN N'@exclude_databases' THEN 'comma-separated list of databases to exclude (only when @get_all_databases = 1)'
WHEN N'@workdays' THEN 'use this to filter out weekends and after-hours queries'
WHEN N'@work_start' THEN 'use this to set a specific start of your work days'
WHEN N'@work_end' THEN 'use this to set a specific end of your work days'
WHEN N'@regression_baseline_start_date' THEN 'the begin date of the baseline that you are checking for regressions against (if any), will be converted to UTC internally'
WHEN N'@regression_baseline_end_date' THEN 'the end date of the baseline that you are checking for regressions against (if any), will be converted to UTC internally'
WHEN N'@regression_comparator' THEN 'what difference to use (''relative'' or ''absolute'') when comparing @sort_order''s metric for the normal time period with any regression time period.'
WHEN N'@regression_direction' THEN 'when comparing against any regression baseline, what do you want the results sorted by (''magnitude'', ''improved'', or ''regressed'')?'
WHEN N'@include_query_hash_totals' THEN N'will add an additional column to final output with total resource usage by query hash, may be skewed by query_hash and query_plan_hash bugs with forced plans/plan guides'
WHEN N'@include_maintenance' THEN N'Set this bit to 1 to add maintenance operations such as index creation to the result set'
WHEN N'@find_high_impact' THEN N'finds the vital few queries consuming disproportionate resources across cpu, duration, reads, writes, memory, and executions'
WHEN N'@primary_window' THEN N'with @find_high_impact, restricts results to queries whose majority activity is in this window (business, off-hours, or weekend)'
WHEN N'@help' THEN 'how you got here'
WHEN N'@debug' THEN 'prints dynamic sql, statement length, parameter and variable values, and raw temp table contents'
WHEN N'@troubleshoot_performance' THEN 'set statistics xml on for queries against views'
WHEN N'@log_to_table' THEN 'enable logging to permanent tables instead of returning results'
WHEN N'@log_database_name' THEN 'database to store logging tables'
WHEN N'@log_schema_name' THEN 'schema to store logging tables'
WHEN N'@log_table_name_prefix' THEN 'prefix for all logging table names'
WHEN N'@log_retention_days' THEN 'days of data to retain, 0 = keep indefinitely'
WHEN N'@version' THEN 'OUTPUT; for support'
WHEN N'@version_date' THEN 'OUTPUT; for support'
END,
valid_inputs =
CASE
ap.name
WHEN N'@database_name' THEN 'a database name with query store enabled'
WHEN N'@sort_order' THEN 'cpu, logical reads, physical reads, writes, duration, memory, tempdb, executions, recent, plan count by hashes, cpu waits, lock waits, locks waits, latch waits, latches waits, buffer latch waits, buffer latches waits, buffer io waits, log waits, log io waits, network waits, network io waits, parallel waits, parallelism waits, memory waits, total waits, rows, total cpu, total logical reads, total physical reads, total writes, total duration, total memory, total tempdb, total rows (avg/average prefix also accepted, e.g. avg cpu, average duration)'
WHEN N'@top' THEN 'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN N'@start_date' THEN 'January 1, 1753, through December 31, 9999'
WHEN N'@end_date' THEN 'January 1, 1753, through December 31, 9999'
WHEN N'@timezone' THEN 'SELECT tzi.* FROM sys.time_zone_info AS tzi;'
WHEN N'@execution_count' THEN 'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN N'@duration_ms' THEN 'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN N'@execution_type_desc' THEN 'regular, aborted, exception'
WHEN N'@procedure_schema' THEN 'a valid schema in your database'
WHEN N'@procedure_name' THEN 'a valid programmable object in your database, can use wildcards'
WHEN N'@include_plan_ids' THEN 'a string; comma separated for multiple ids'
WHEN N'@include_query_ids' THEN 'a string; comma separated for multiple ids'
WHEN N'@include_query_hashes' THEN 'a string; comma separated for multiple hashes'
WHEN N'@include_plan_hashes' THEN 'a string; comma separated for multiple hashes'
WHEN N'@include_sql_handles' THEN 'a string; comma separated for multiple handles'
WHEN N'@ignore_plan_ids' THEN 'a string; comma separated for multiple ids'
WHEN N'@ignore_query_ids' THEN 'a string; comma separated for multiple ids'
WHEN N'@ignore_query_hashes' THEN 'a string; comma separated for multiple hashes'
WHEN N'@ignore_plan_hashes' THEN 'a string; comma separated for multiple hashes'
WHEN N'@ignore_sql_handles' THEN 'a string; comma separated for multiple handles'
WHEN N'@query_text_search' THEN 'a string; leading and trailing wildcards will be added if missing'
WHEN N'@query_text_search_not' THEN 'a string; leading and trailing wildcards will be added if missing'
WHEN N'@escape_brackets' THEN '0 or 1'
WHEN N'@escape_character' THEN 'some escape character, SQL standard is backslash (\)'
WHEN N'@only_queries_with_hints' THEN '0 or 1'
WHEN N'@only_queries_with_feedback' THEN '0 or 1'
WHEN N'@only_queries_with_variants' THEN '0 or 1'
WHEN N'@only_queries_with_forced_plans' THEN '0 or 1'
WHEN N'@only_queries_with_forced_plan_failures' THEN '0 or 1'
WHEN N'@wait_filter' THEN 'cpu, lock, latch, buffer latch, buffer io, log io, network io, parallelism, memory'
WHEN N'@query_type' THEN 'ad hoc, adhoc, proc, procedure, whatever.'
WHEN N'@expert_mode' THEN '0 or 1'
WHEN N'@hide_help_table' THEN '0 or 1'
WHEN N'@format_output' THEN '0 or 1'
WHEN N'@get_all_databases' THEN '0 or 1'
WHEN N'@include_databases' THEN 'a string; comma separated database names'
WHEN N'@exclude_databases' THEN 'a string; comma separated database names'
WHEN N'@workdays' THEN '0 or 1'
WHEN N'@work_start' THEN 'a time like 8am, 9am or something'
WHEN N'@work_end' THEN 'a time like 5pm, 6pm or something'
WHEN N'@regression_baseline_start_date' THEN 'January 1, 1753, through December 31, 9999'
WHEN N'@regression_baseline_end_date' THEN 'January 1, 1753, through December 31, 9999'
WHEN N'@regression_comparator' THEN 'relative, absolute'
WHEN N'@regression_direction' THEN 'regressed, worse, improved, better, magnitude, absolute, whatever'
WHEN N'@include_query_hash_totals' THEN N'0 or 1'
WHEN N'@include_maintenance' THEN N'0 or 1'
WHEN N'@find_high_impact' THEN N'0 or 1'
WHEN N'@primary_window' THEN N'business, off-hours, or weekend (any unambiguous prefix works: b, biz, off, overnight, w, wknd, etc.)'
WHEN N'@help' THEN '0 or 1'
WHEN N'@debug' THEN '0 or 1'
WHEN N'@troubleshoot_performance' THEN '0 or 1'
WHEN N'@log_to_table' THEN '0 or 1'
WHEN N'@log_database_name' THEN 'a valid database name'
WHEN N'@log_schema_name' THEN 'a valid schema name'
WHEN N'@log_table_name_prefix' THEN 'a valid identifier'
WHEN N'@log_retention_days' THEN 'a positive integer, or 0'
WHEN N'@version' THEN 'none; OUTPUT'
WHEN N'@version_date' THEN 'none; OUTPUT'
END,
defaults =
CASE
ap.name
WHEN N'@database_name' THEN 'NULL; current database name if NULL'
WHEN N'@sort_order' THEN 'cpu'
WHEN N'@top' THEN '10'
WHEN N'@start_date' THEN 'the last seven days'
WHEN N'@end_date' THEN 'NULL'
WHEN N'@timezone' THEN 'NULL'
WHEN N'@execution_count' THEN 'NULL'
WHEN N'@duration_ms' THEN 'NULL'
WHEN N'@execution_type_desc' THEN 'NULL'
WHEN N'@procedure_schema' THEN 'NULL; dbo if NULL and procedure name is not NULL'
WHEN N'@procedure_name' THEN 'NULL'
WHEN N'@include_plan_ids' THEN 'NULL'
WHEN N'@include_query_ids' THEN 'NULL'
WHEN N'@include_query_hashes' THEN 'NULL'
WHEN N'@include_plan_hashes' THEN 'NULL'
WHEN N'@include_sql_handles' THEN 'NULL'
WHEN N'@ignore_plan_ids' THEN 'NULL'
WHEN N'@ignore_query_ids' THEN 'NULL'
WHEN N'@ignore_query_hashes' THEN 'NULL'
WHEN N'@ignore_plan_hashes' THEN 'NULL'
WHEN N'@ignore_sql_handles' THEN 'NULL'
WHEN N'@query_text_search' THEN 'NULL'
WHEN N'@query_text_search_not' THEN 'NULL'
WHEN N'@escape_brackets' THEN '0'
WHEN N'@escape_character' THEN '\'
WHEN N'@only_queries_with_hints' THEN '0'
WHEN N'@only_queries_with_feedback' THEN '0'
WHEN N'@only_queries_with_variants' THEN '0'
WHEN N'@only_queries_with_forced_plans' THEN '0'
WHEN N'@only_queries_with_forced_plan_failures' THEN '0'
WHEN N'@wait_filter' THEN 'NULL'
WHEN N'@query_type' THEN 'NULL'
WHEN N'@expert_mode' THEN '0'
WHEN N'@hide_help_table' THEN '0'
WHEN N'@format_output' THEN '1'
WHEN N'@get_all_databases' THEN '0'
WHEN N'@include_databases' THEN 'NULL'
WHEN N'@exclude_databases' THEN 'NULL'
WHEN N'@workdays' THEN '0'
WHEN N'@work_start' THEN '9am'
WHEN N'@work_end' THEN '5pm'
WHEN N'@regression_baseline_start_date' THEN 'NULL'
WHEN N'@regression_baseline_end_date' THEN 'NULL; One week after @regression_baseline_start_date if that is specified'
WHEN N'@regression_comparator' THEN 'NULL; absolute if @regression_baseline_start_date is specified'
WHEN N'@regression_direction' THEN 'NULL; regressed if @regression_baseline_start_date is specified'
WHEN N'@include_query_hash_totals' THEN N'0'
WHEN N'@include_maintenance' THEN N'0'
WHEN N'@find_high_impact' THEN N'0'
WHEN N'@primary_window' THEN N'NULL'
WHEN N'@help' THEN '0'
WHEN N'@debug' THEN '0'
WHEN N'@troubleshoot_performance' THEN '0'
WHEN N'@log_to_table' THEN '0'
WHEN N'@log_database_name' THEN 'NULL; current database'
WHEN N'@log_schema_name' THEN 'NULL; dbo'
WHEN N'@log_table_name_prefix' THEN 'QuickieStore'
WHEN N'@log_retention_days' THEN '30'
WHEN N'@version' THEN 'none; OUTPUT'
WHEN N'@version_date' THEN 'none; OUTPUT'
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_QuickieStore'
ORDER BY
ap.parameter_id
OPTION(RECOMPILE);
/*
Wait categories: Only 2017+
*/
IF EXISTS
(
SELECT
1/0
FROM sys.all_objects AS ao
WHERE ao.name = N'query_store_wait_stats'
)
BEGIN
SELECT
wait_categories =
'cpu (1): SOS_SCHEDULER_YIELD' UNION ALL
SELECT 'lock (3): LCK_M_%' UNION ALL
SELECT 'latch (4): LATCH_%' UNION ALL
SELECT 'buffer latch (5): PAGELATCH_%' UNION ALL
SELECT 'buffer io (6): PAGEIOLATCH_%' UNION ALL
SELECT 'log io (14): LOGMGR, LOGBUFFER, LOGMGR_RESERVE_APPEND, LOGMGR_FLUSH, LOGMGR_PMM_LOG, CHKPT, WRITELOG' UNION ALL
SELECT 'network io (15): ASYNC_NETWORK_IO, NET_WAITFOR_PACKET, PROXY_NETWORK_IO, EXTERNAL_SCRIPT_NETWORK_IOF' UNION ALL
SELECT 'parallelism (16): CXPACKET, EXCHANGE, HT%, BMP%, BP%' UNION ALL
SELECT 'memory (17): RESOURCE_SEMAPHORE, CMEMTHREAD, CMEMPARTITIONED, EE_PMOLOCK, MEMORY_ALLOCATION_EXT, RESERVED_MEMORY_ALLOCATION_EXT, MEMORY_GRANT_UPDATE';
END;
/*
Results
*/
SELECT
results =
'results returned at the end of the procedure:' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Runtime Stats: data from query_store_runtime_stats, along with query plan, query text, wait stats (2017+, when enabled), and parent object' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Compilation Stats (expert mode only): data from query_store_query about compilation metrics' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Resource Stats (expert mode only): data from dm_exec_query_stats, when available' UNION ALL
SELECT 'query store does not currently track some details about memory grants and thread usage' UNION ALL
SELECT 'so i go back to a plan cache view to try to track it down' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Store Plan Feedback (2022+, expert mode, or when using only_queries_with_feedback): Lists queries that have been adjusted based on automated feedback mechanisms' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Store Hints (2022+, expert mode or when using @only_queries_with_hints): lists hints applied to queries from automated feedback mechanisms' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Variants (2022+, expert mode or when using @only_queries_with_variants): lists plan variants from the Parameter Sensitive Plan feedback mechanism' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Store Waits By Query (2017+, expert mode only): information about query duration and logged wait stats' UNION ALL
SELECT 'it can sometimes be useful to compare query duration to query wait times' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Store Waits Total (2017+, expert mode only): total wait stats for the chosen date range only' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Replicas (2022+, expert mode only): lists plans forced on AG replicas' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'Query Store Options (expert mode only): details about current query store configuration';
/*
High Impact column guide
*/
SELECT
high_impact_columns =
'when using @find_high_impact = 1, the result set contains these columns:' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'database_name: the database being analyzed' UNION ALL
SELECT 'start_date, end_date: the time window analyzed (UTC)' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'primary_window: when this query runs most. Business (during @work_start to @work_end on weekdays),' UNION ALL
SELECT ' Off-hours (weekday nights), Weekend, or Spread (no single window > 50%). Percentage shown.' UNION ALL
SELECT ' Use @primary_window = ''business'' / ''off-hours'' / ''weekend'' to filter to queries whose majority activity falls in that window.' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'object_name: the stored procedure, function, or trigger this query belongs to, or "Adhoc" for ad hoc SQL' UNION ALL
SELECT 'query_sql_text: representative query text (the most-executed variant for this query_hash)' UNION ALL
SELECT 'query_plan: the most recent execution plan (XML) for this query_hash' UNION ALL
SELECT 'top_waits: top 3 Query Store wait categories with total wait time in ms (SQL 2017+ with wait stats enabled, omitted otherwise)' UNION ALL
SELECT 'query_hash: the query_hash that groups all parameterized variants of the same query' UNION ALL
SELECT 'query_count: how many distinct query_ids share this hash (parameterized variants)' UNION ALL
SELECT 'plan_count: how many distinct plans exist across all variants. >1 may indicate plan instability.' UNION ALL
SELECT 'query_id_list, plan_id_list: comma-separated IDs for drilling into Query Store views' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'impact_score: 0.00 to 1.00. The average PERCENT_RANK across all active resource dimensions.' UNION ALL
SELECT ' 0.90 means this query outranks 90% of all queries in the database on the metrics where it registers.' UNION ALL
SELECT ' Only queries scoring >= 0.50 are shown. A dimension is "active" when the query accounts for >= 0.1% of the total.' UNION ALL
SELECT 'high_signals: which dimensions scored above the 80th percentile (e.g. "cpu, duration, physical reads")' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'total_executions: how many times this query_hash executed in the time window' UNION ALL
SELECT 'cpu_share, duration_share, physical_reads_share, writes_share, memory_share, executions_share:' UNION ALL
SELECT ' what percentage of the server''s total for that metric this single query_hash consumed.' UNION ALL
SELECT ' This is the 80/20 answer: "this one query is X% of all CPU on the server."' UNION ALL
SELECT 'resource_metrics: clickable XML rollup of total/avg/min/max for cpu, duration, physical reads, writes, memory,' UNION ALL
SELECT ' tempdb, executions, rows, and max DOP. Click the column in SSMS to see the full breakdown.' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'diagnostics: rule-based signals layered on top of the score:' UNION ALL
SELECT ' wait time (dur/cpu=Nx) - duration far exceeds CPU time, meaning the query spends most of its time waiting' UNION ALL
SELECT ' (blocking, resource contention, I/O). The multiplier shows how much worse duration is vs CPU.' UNION ALL
SELECT ' param sensitive (1 plan, cpu Nx) - single plan but wildly varying CPU times across executions.' UNION ALL
SELECT ' Classic parameter sniffing: one plan shape that works for some parameter values but not others.' UNION ALL
SELECT ' plan instability (N plans) - multiple plans with fewer than 5 executions per plan, excluding RECOMPILE hints.' UNION ALL
SELECT ' The optimizer keeps recompiling frequently, which usually means inconsistent performance.' UNION ALL
SELECT ' spills/spools (N MB/exec) - writes detected on a SELECT-like query (no INSERT/UPDATE/DELETE/MERGE).' UNION ALL
SELECT ' This typically means tempdb spills from underestimated memory grants, or worktable spools.' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'volatile_metrics: flags metrics with extreme variance: (max - min) / avg > 10x.' UNION ALL
SELECT ' Only flagged when the absolute max exceeds meaningful thresholds (1s duration, 100ms CPU, 1MB physical reads/writes/memory).' UNION ALL
SELECT ' High volatility means the query''s performance is unpredictable, even if the average looks acceptable.' UNION ALL
SELECT REPLICATE('-', 100) UNION ALL
SELECT 'WORKLOAD CONCENTRATION SUMMARY (separate result set, returned before the query details):' UNION ALL
SELECT 'total_query_hashes: how many distinct query_hashes had executions in the time window' UNION ALL
SELECT 'surfaced_query_hashes: how many made it into the detail result set after top-N and scoring filters' UNION ALL
SELECT 'top_n_cpu_pct, top_n_duration_pct, top_n_reads_pct, top_n_writes_pct, top_n_memory_pct, top_n_executions_pct:' UNION ALL
SELECT ' what percentage of the server''s total for each metric the surfaced queries account for.' UNION ALL
SELECT ' If top_n_cpu_pct = 88.2, the surfaced queries are 88.2% of all CPU in the time window.' UNION ALL
SELECT 'workload_profile: Concentrated (>= 50%), Moderate (25-49%), or Flat (< 25%).' UNION ALL
SELECT ' Based on the highest concentration across all six metrics.' UNION ALL
SELECT ' Concentrated: a few queries dominate. Tuning them individually will have the most impact.' UNION ALL
SELECT ' Moderate: some outliers, but a long tail of smaller queries also matters.' UNION ALL
SELECT ' Flat: no dominant queries. Individual query tuning has limited value.' UNION ALL
SELECT 'recommendation: actionable guidance based on the workload profile.' UNION ALL
SELECT ' For flat workloads: consider forced parameterization, look for missing schema prefixes,' UNION ALL
SELECT ' temp table patterns causing recompilation, or RECOMPILE hints generating unique plans.';
/*
Limitations
*/
SELECT
limitations =
'frigid shortcomings:' UNION ALL
SELECT 'you need to be on at least SQL Server 2016 SP2, 2017 CU3, or any higher version to run this' UNION ALL
SELECT 'if you''re on azure sql db then you''ll need to be in compat level 130' UNION ALL
SELECT 'i do not currently support synapse or edge or other memes, and azure sql db support is not guaranteed';
/*
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; /*End @help section*/
/*
Normalize Sort Order.
Allow avg/average prefix for backwards compatibility,
e.g. 'avg cpu' or 'average cpu' maps to 'cpu'.
*/
IF LOWER(@sort_order) LIKE 'average %'
BEGIN
SELECT
@sort_order = LTRIM(SUBSTRING(@sort_order, 9, LEN(@sort_order)));
END;
IF LOWER(@sort_order) LIKE 'avg %'
BEGIN
SELECT
@sort_order = LTRIM(SUBSTRING(@sort_order, 5, LEN(@sort_order)));
END;
/*
Validate Sort Order.
We do this super early on, because we care about it even
when populating the tables that we declare very soon.
*/
IF @sort_order NOT IN
(
'cpu',
'logical reads',
'physical reads',
'writes',
'duration',
'memory',
'tempdb',
'executions',
'recent',
'plan count by hashes',
'cpu waits',
'lock waits',
'locks waits',
'latch waits',
'latches waits',
'buffer latch waits',
'buffer latches waits',
'buffer io waits',
'log waits',
'log io waits',
'network waits',
'network io waits',
'parallel waits',
'parallelism waits',
'memory waits',
'total waits',
'rows',
'total cpu',
'total logical reads',
'total physical reads',
'total writes',
'total duration',
'total memory',
'total tempdb',
'total rows'
)
BEGIN
RAISERROR('The sort order (%s) you chose is so out of this world that I''m using cpu instead', 10, 1, @sort_order) WITH NOWAIT;
SELECT
@sort_order = 'cpu';
END;
DECLARE
@sort_order_is_a_wait bit;
/*
Checks if the sort order is for a wait.
Cuts out a lot of repetition.
*/
IF LOWER(@sort_order) IN
(
'cpu waits',
'lock waits',
'locks waits',
'latch waits',
'latches waits',
'buffer latch waits',
'buffer latches waits',
'buffer io waits',
'log waits',
'log io waits',
'network waits',
'network io waits',
'parallel waits',
'parallelism waits',
'memory waits',
'total waits'
)
BEGIN
SELECT
@sort_order_is_a_wait = 1;
END;
/*
We also validate regression mode super early.
We need to do this here so we can build @ColumnDefinitions correctly.
It also lets us fail fast, if needed.
*/
DECLARE
@regression_mode bit;
/*
Set @regression_mode if the given arguments indicate that
we are checking for regressed queries.
Also set any default parameters for regression mode while we're at it.
*/
IF @regression_baseline_start_date IS NOT NULL
BEGIN
SELECT
@regression_mode = 1,
@regression_comparator =
ISNULL(@regression_comparator, 'absolute'),
@regression_direction =
ISNULL(@regression_direction, 'regressed');
END;
/*
Error out if the @regression parameters do not make sense.
*/
IF
(
@regression_baseline_start_date IS NULL
AND
(
@regression_baseline_end_date IS NOT NULL
OR @regression_comparator IS NOT NULL
OR @regression_direction IS NOT NULL
)
)
BEGIN
RAISERROR('@regression_baseline_start_date is mandatory if you have specified any other @regression_ parameter.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Error out if the @regression_baseline_start_date and
@regression_baseline_end_date are incompatible.
We could try and guess a sensible resolution, but
I do not think that we can know what people want.
*/
IF
(
@regression_baseline_start_date IS NOT NULL
AND @regression_baseline_end_date IS NOT NULL
AND @regression_baseline_start_date >= @regression_baseline_end_date
)
BEGIN
RAISERROR('@regression_baseline_start_date has been set greater than or equal to @regression_baseline_end_date.
This does not make sense. Check that the values of both parameters are as you intended them to be.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Validate @regression_comparator.
*/
IF
(
@regression_comparator IS NOT NULL
AND @regression_comparator NOT IN ('relative', 'absolute')
)
BEGIN
RAISERROR('The regression_comparator (%s) you chose is so out of this world that I''m using ''absolute'' instead', 10, 1, @regression_comparator) WITH NOWAIT;
SELECT
@regression_comparator = 'absolute';
END;
/*
Validate @regression_direction.
*/
IF
(
@regression_direction IS NOT NULL
AND @regression_direction NOT IN ('regressed', 'worse', 'improved', 'better', 'magnitude', 'absolute')
)
BEGIN
RAISERROR('The regression_direction (%s) you chose is so out of this world that I''m using ''regressed'' instead', 10, 1, @regression_direction) WITH NOWAIT;
SELECT
@regression_direction = 'regressed';
END;
/*
Error out if we're trying to do regression mode with 'recent'
as our @sort_order. How could that ever make sense?
*/
IF
(
@regression_mode = 1
AND @sort_order = 'recent'
)
BEGIN
RAISERROR('Your @sort_order is ''recent'', but you are trying to compare metrics for two time periods.
If you can imagine a useful way to do that, then make a feature request.
Otherwise, either stop specifying any @regression_ parameters or specify a different @sort_order.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Error out if we're trying to do regression mode with 'plan count by hashes'
as our @sort_order. How could that ever make sense?
*/
IF
(
@regression_mode = 1
AND @sort_order = 'plan count by hashes'
)
BEGIN
RAISERROR('Your @sort_order is ''plan count by hashes'', but you are trying to compare metrics for two time periods.
This is probably not useful, since our method of comparing two time period relies on only checking query hashes that are in both time periods.
If you can imagine a useful way to do that, then make a feature request.
Otherwise, either stop specifying any @regression_ parameters or specify a different @sort_order.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Error out if @regression_comparator tells us to use division,
but @regression_direction tells us to take the modulus.
It doesn't make sense to specifically ask us to remove the sign
of something that doesn't care about it.
*/
IF
(
@regression_comparator = 'relative'
AND @regression_direction IN ('absolute', 'magnitude')
)
BEGIN
RAISERROR('Your @regression_comparator is ''relative'', but you have asked for an ''absolute'' or ''magnitude'' @regression_direction. This is probably a mistake.
Your @regression_direction tells us to take the absolute value of our result of comparing the metrics in the current time period to the baseline time period,
but your @regression_comparator is telling us to use division to compare the two time periods. This is unlikely to produce useful results.
If you can imagine a useful way to do that, then make a feature request. Otherwise, either change @regression_direction to another value
(e.g. ''better'' or ''worse'') or change @regression_comparator to ''absolute''.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
@find_high_impact can't be used with @get_all_databases
because the results would be diluted across databases
*/
IF
(
@find_high_impact = 1
AND @get_all_databases = 1
)
BEGIN
RAISERROR('@find_high_impact cannot be used with @get_all_databases. Run @find_high_impact against each database individually.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
@log_to_table can't be used with @find_high_impact
because @find_high_impact takes a completely separate code path
*/
IF
(
@log_to_table = 1
AND @find_high_impact = 1
)
BEGIN
RAISERROR('@log_to_table cannot be used with @find_high_impact. Run them separately.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
@primary_window only applies to the @find_high_impact path, and must
match one of the three bucket labels by case-insensitive prefix: b/o/w
*/
IF @primary_window IS NOT NULL
BEGIN
IF @find_high_impact = 0
BEGIN
RAISERROR('@primary_window only applies when @find_high_impact = 1.', 11, 1) WITH NOWAIT;
RETURN;
END;
IF LOWER(@primary_window) NOT LIKE N'b%'
AND LOWER(@primary_window) NOT LIKE N'o%'
AND LOWER(@primary_window) NOT LIKE N'w%'
BEGIN
RAISERROR('@primary_window must start with b (business), o (off-hours), or w (weekend).', 11, 1) WITH NOWAIT;
RETURN;
END;
END;
/*
These are the tables that we'll use to grab data from query store
It will be fun
You'll love it
*/
/*
Plans we'll be working on
*/
CREATE TABLE
#distinct_plans
(
plan_id bigint PRIMARY KEY CLUSTERED
);
/*
Hold plan_ids for procedures we're searching
*/
CREATE TABLE
#procedure_plans
(
plan_id bigint PRIMARY KEY CLUSTERED
);
/*
Hold plan_ids for procedures we're searching
*/
CREATE TABLE
#procedure_object_ids
(
[object_id] bigint PRIMARY KEY CLUSTERED
);
/*
Hold plan_ids for ad hoc or procedures we're searching for
*/
CREATE TABLE
#query_types
(
plan_id bigint PRIMARY KEY CLUSTERED
);
/*
Hold plan_ids for plans we want
*/
CREATE TABLE
#include_plan_ids
(
plan_id bigint PRIMARY KEY CLUSTERED
WITH (IGNORE_DUP_KEY = ON)
);
/*
Hold query_ids for plans we want
*/
CREATE TABLE
#include_query_ids
(
query_id bigint PRIMARY KEY CLUSTERED
);
/*
Hold plan_ids for ignored plans
*/
CREATE TABLE
#ignore_plan_ids
(
plan_id bigint PRIMARY KEY CLUSTERED
WITH (IGNORE_DUP_KEY = ON)
);
/*
Hold query_ids for ignored plans
*/
CREATE TABLE
#ignore_query_ids
(
query_id bigint PRIMARY KEY CLUSTERED
);
/*
Hold query hashes for plans we want
*/
CREATE TABLE
#include_query_hashes
(
query_hash_s varchar(131),
query_hash AS
CONVERT
(
binary(8),
query_hash_s,
1
) PERSISTED NOT NULL
PRIMARY KEY CLUSTERED
);
/*
For filtering by @execution_count.
This is only used for filtering, so it only needs one column.
*/
CREATE TABLE
#plan_ids_having_enough_executions
(
plan_id bigint PRIMARY KEY CLUSTERED,
);
/*
The following two tables are for adding extra columns
on to our output. We need these for sorting by anything
that isn't in #query_store_runtime_stats.
We still have to declare these tables even when they're
not used because the debug output breaks if we don't.
They are database dependent but not truncated at
the end of each loop, so we need a database_id
column.
We do not truncate these because we need them to still
be in scope and fully populated when we return our
final results from #query_store_runtime_stats, which
is done after the point where we would truncate.
*/
/*
Holds plan_id with the count of the number of query hashes they have.
Only used when we're sorting by how many plan hashes each
query hash has.
*/
CREATE TABLE
#plan_ids_with_query_hashes
(
database_id integer NOT NULL,
plan_id bigint NOT NULL,
query_hash binary(8) NOT NULL,
plan_hash_count_for_query_hash integer NOT NULL,
PRIMARY KEY CLUSTERED (database_id, plan_id, query_hash)
);
/*
Largely just exists because total_query_wait_time_ms
isn't in our normal output.
Unfortunately needs an extra column for regression
mode's benefit. The alternative was either a
horrible UNPIVOT with an extra temp table
or changing @parameters everywhere (and
therefore every sp_executesql).
*/
CREATE TABLE
#plan_ids_with_total_waits
(
database_id integer NOT NULL,
plan_id bigint NOT NULL,
from_regression_baseline varchar(3) NOT NULL,
total_query_wait_time_ms bigint NOT NULL,
PRIMARY KEY CLUSTERED(database_id, plan_id, from_regression_baseline)
);
/*
Used in regression mode to hold the
statistics for each query hash in our
baseline time period.
*/
CREATE TABLE
#regression_baseline_runtime_stats
(
query_hash binary(8) NOT NULL PRIMARY KEY CLUSTERED,
/* Nullable to protect from division by 0. */
regression_metric_average float NULL
);
/*
Used in regression mode to hold the
statistics for each query hash in our
normal time period.
*/
CREATE TABLE
#regression_current_runtime_stats
(
query_hash binary(8) NOT NULL PRIMARY KEY CLUSTERED,
/* Nullable to protect from division by 0. */
current_metric_average float NULL
);
/*
Used in regression mode to hold the
results of comparing our two time
periods.
This is also used just like a