-
Notifications
You must be signed in to change notification settings - Fork 84
/
sp_QuickieStore - Erik Darling.sql
4583 lines (4100 loc) · 165 KB
/
sp_QuickieStore - Erik Darling.sql
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
-- sp_QuickieStore - Erik Darling
-- Part of the SQL Server DBA Toolbox at https://github.com/DavidSchanzer/Sql-Server-DBA-Toolbox
-- This script creates Erik Darling's sp_QuickieStore stored procedure that "digs into Query Store data to find queries to tune".
-- From https://github.com/erikdarlingdata/DarlingData/blob/main/sp_QuickieStore/sp_QuickieStore.sql
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 IMPLICIT_TRANSACTIONS OFF;
SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;
GO
/*
██████╗ ██╗ ██╗██╗ ██████╗██╗ ██╗██╗███████╗
██╔═══██╗██║ ██║██║██╔════╝██║ ██╔╝██║██╔════╝
██║ ██║██║ ██║██║██║ █████╔╝ ██║█████╗
██║▄▄ ██║██║ ██║██║██║ ██╔═██╗ ██║██╔══╝
╚██████╔╝╚██████╔╝██║╚██████╗██║ ██╗██║███████╗
╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚══════╝
███████╗████████╗ ██████╗ ██████╗ ███████╗██╗
██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝██║
███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║
╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ╚═╝
███████║ ██║ ╚██████╔╝██║ ██║███████╗██╗
╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝
Copyright 2021 Darling Data, LLC
https://www.erikdarlingdata.com/
For usage and licensing details, run:
EXEC sp_QuickieStore
@help = 1;
For working through errors:
EXEC sp_QuickieStore
@debug = 1;
For performance issues:
EXEC sp_QuickieStore
@troubleshoot_performance = 1;
For support, head over to GitHub:
https://github.com/erikdarlingdata/DarlingData
*/
CREATE OR ALTER PROCEDURE dbo.sp_QuickieStore
(
@database_name sysname = NULL,
@sort_order VARCHAR(20) = 'cpu',
@top BIGINT = 10,
@start_date DATETIME = NULL,
@end_date DATETIME = NULL,
@execution_count BIGINT = NULL,
@duration_ms BIGINT = NULL,
@procedure_schema sysname = NULL,
@procedure_name sysname = NULL,
@include_plan_ids NVARCHAR(4000) = NULL,
@include_query_ids NVARCHAR(4000) = NULL,
@ignore_plan_ids NVARCHAR(4000) = NULL,
@ignore_query_ids NVARCHAR(4000) = NULL,
@query_text_search NVARCHAR(4000) = NULL,
@wait_filter VARCHAR(20) = NULL,
@expert_mode BIT = 0,
@format_output BIT = 0,
@version VARCHAR(30) = NULL OUTPUT,
@version_date DATETIME = NULL OUTPUT,
@help BIT = 0,
@debug BIT = 0,
@troubleshoot_performance BIT = 0
)
WITH RECOMPILE
AS
BEGIN
SET STATISTICS XML OFF;
SET NOCOUNT, XACT_ABORT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
BEGIN TRY
/*
If this column doesn't exist, you're not on a good version of SQL Server
*/
IF NOT EXISTS
(
SELECT 1 / 0
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_exec_query_stats', N'V')
AND ac.name = N'total_spills'
)
BEGIN
RAISERROR(
'This procedure only runs on supported versions of SQL Server:
* 2016 SP2+
* 2017 CU3+
* 2019+
* Probably Azure?',
11,
1
) WITH NOWAIT;
RETURN;
END;
/*
These are for your outputs.
*/
SELECT @version = '1.92',
@version_date = '20211101';
/*
Helpful section! For help.
*/
IF @help = 1
BEGIN
/*
Introduction
*/
SELECT introduction = 'hi, i''m sp_QuickieStore!'
UNION ALL
SELECT 'you got me from https://www.erikdarlingdata.com/sp_quickiestore/'
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!';
/*
Parameters
*/
SELECT parameter_name = ap.name,
data_type = t.name,
description = CASE ap.name
WHEN '@database_name' THEN
'the name of the database you want to look at query store in'
WHEN '@sort_order' THEN
'the runtime metric you want to prioritize results by'
WHEN '@top' THEN
'the number of queries you want to pull back'
WHEN '@start_date' THEN
'the begin date of your search'
WHEN '@end_date' THEN
'the end date of your search'
WHEN '@execution_count' THEN
'the minimum number of executions a query must have'
WHEN '@duration_ms' THEN
'the minimum duration a query must have'
WHEN '@procedure_schema' THEN
'the schema of the procedure you''re searching for'
WHEN '@procedure_name' THEN
'the name of the programmable object you''re searching for'
WHEN '@include_plan_ids' THEN
'a list of plan ids to search for'
WHEN '@include_query_ids' THEN
'a list of query ids to search for'
WHEN '@ignore_plan_ids' THEN
'a list of plan ids to ignore'
WHEN '@ignore_query_ids' THEN
'a list of query ids to ignore'
WHEN '@query_text_search' THEN
'query text to search for'
WHEN '@wait_filter' THEN
'wait category to search for; category details are below'
WHEN '@expert_mode' THEN
'returns additional columns and results'
WHEN '@format_output' THEN
'returns numbers formatted with commas'
WHEN '@version' THEN
'OUTPUT; for support'
WHEN '@version_date' THEN
'OUTPUT; for support'
WHEN '@help' THEN
'how you got here'
WHEN '@debug' THEN
'prints dynamic sql (including statement length), parameter and variable values, and raw temp table contents'
WHEN '@troubleshoot_performance' THEN
'set statistics xml on for queries against views'
END,
valid_inputs = CASE ap.name
WHEN '@database_name' THEN
'a database name with query store enabled'
WHEN '@sort_order' THEN
'cpu, logical reads, physical reads, writes, duration, memory, tempdb, executions'
WHEN '@top' THEN
'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN '@start_date' THEN
'January 1, 1753, through December 31, 9999'
WHEN '@end_date' THEN
'January 1, 1753, through December 31, 9999'
WHEN '@execution_count' THEN
'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN '@duration_ms' THEN
'a positive integer between 1 and 9,223,372,036,854,775,807'
WHEN '@procedure_schema' THEN
'a valid schema in your database'
WHEN '@procedure_name' THEN
'a valid programmable object in your database'
WHEN '@include_plan_ids' THEN
'a string; comma separated for multiple ids'
WHEN '@include_query_ids' THEN
'a string; comma separated for multiple ids'
WHEN '@ignore_plan_ids' THEN
'a string; comma separated for multiple ids'
WHEN '@ignore_query_ids' THEN
'a string; comma separated for multiple ids'
WHEN '@query_text_search' THEN
'a string; leading and trailing wildcards will be added if missing'
WHEN '@wait_filter' THEN
'cpu, lock, latch, buffer latch, buffer io, log io, network io, parallelism, memory'
WHEN '@expert_mode' THEN
'0 or 1'
WHEN '@format_output' THEN
'0 or 1'
WHEN '@version' THEN
'none'
WHEN '@version_date' THEN
'none'
WHEN '@help' THEN
'0 or 1'
WHEN '@debug' THEN
'0 or 1'
WHEN '@troubleshoot_performance' THEN
'0 or 1'
END,
defaults = CASE ap.name
WHEN '@database_name' THEN
'NULL'
WHEN '@sort_order' THEN
'cpu'
WHEN '@top' THEN
'10'
WHEN '@start_date' THEN
'the last 24 hours'
WHEN '@end_date' THEN
'NULL'
WHEN '@execution_count' THEN
'NULL'
WHEN '@duration_ms' THEN
'NULL'
WHEN '@procedure_schema' THEN
'NULL; dbo if NULL and procedure name is not NULL'
WHEN '@procedure_name' THEN
'NULL'
WHEN '@include_plan_ids' THEN
'NULL'
WHEN '@include_query_ids' THEN
'NULL'
WHEN '@ignore_plan_ids' THEN
'NULL'
WHEN '@ignore_query_ids' THEN
'NULL'
WHEN '@query_text_search' THEN
'NULL'
WHEN '@wait_filter' THEN
'NULL'
WHEN '@expert_mode' THEN
'0'
WHEN '@format_output' THEN
'0'
WHEN '@version' THEN
'none'
WHEN '@version_date' THEN
'none'
WHEN '@help' THEN
'0'
WHEN '@debug' THEN
'0'
WHEN '@troubleshoot_performance' THEN
'0'
END
FROM sys.all_parameters AS ap
INNER JOIN sys.all_objects AS o
ON ap.object_id = o.object_id
INNER 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'
OPTION (RECOMPILE);
/*
Wait categories
*/
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';
/*
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 Waits By Query(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(expert mode only): total wait stats for the chosen date range only'
UNION ALL
SELECT REPLICATE('-', 100)
UNION ALL
SELECT 'Query Store Options (expert mode only): details about current query store configuration';
/*
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';
/*
License to F5
*/
SELECT mit_license_yo = 'i am MIT licensed, so like, do whatever'
UNION ALL
SELECT 'see printed messages for full license';
RAISERROR(
'
MIT License
Copyright 2021 Darling Data, LLC
https://www.erikdarlingdata.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;
/*
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
);
/*
Hold plan_ids for procedures we're searching
*/
CREATE TABLE #procedure_plans
(
plan_id BIGINT PRIMARY KEY
);
/*
Hold plan_ids for plans we want
*/
CREATE TABLE #include_plan_ids
(
plan_id BIGINT PRIMARY KEY
);
/*
Hold query_ids for plans we want
*/
CREATE TABLE #include_query_ids
(
query_id BIGINT PRIMARY KEY
);
/*
Hold plan_ids for ignored plans
*/
CREATE TABLE #ignore_plan_ids
(
plan_id BIGINT PRIMARY KEY
);
/*
Hold query_ids for ignored plans
*/
CREATE TABLE #ignore_query_ids
(
query_id BIGINT PRIMARY KEY
);
/*
Hold plan_ids for matching query text
*/
CREATE TABLE #query_text_search
(
plan_id BIGINT PRIMARY KEY
);
/*
Hold plan_ids for matching wait filter
*/
CREATE TABLE #wait_filter
(
plan_id BIGINT PRIMARY KEY
);
/*
Index and statistics entries to avoid
*/
CREATE TABLE #maintenance_plans
(
plan_id BIGINT PRIMARY KEY
);
/*
Query Store Setup
*/
CREATE TABLE #database_query_store_options
(
desired_state_desc NVARCHAR(60) NULL,
actual_state_desc NVARCHAR(60) NULL,
readonly_reason NVARCHAR(100) NULL,
current_storage_size_mb BIGINT NULL,
flush_interval_seconds BIGINT NULL,
interval_length_minutes BIGINT NULL,
max_storage_size_mb BIGINT NULL,
stale_query_threshold_days BIGINT NULL,
max_plans_per_query BIGINT NULL,
query_capture_mode_desc NVARCHAR(60) NULL,
capture_policy_execution_count INT NULL,
capture_policy_total_compile_cpu_time_ms BIGINT NULL,
capture_policy_total_execution_cpu_time_ms BIGINT NULL,
capture_policy_stale_threshold_hours INT NULL,
size_based_cleanup_mode_desc NVARCHAR(60) NULL,
wait_stats_capture_mode_desc NVARCHAR(60) NULL
);
/*
Plans and Plan information
*/
CREATE TABLE #query_store_plan
(
plan_id BIGINT NOT NULL,
query_id BIGINT NOT NULL,
all_plan_ids VARCHAR(MAX),
plan_group_id BIGINT NULL,
engine_version NVARCHAR(32) NULL,
compatibility_level SMALLINT NOT NULL,
query_plan_hash BINARY(8) NOT NULL,
query_plan NVARCHAR(MAX) NULL,
is_online_index_plan BIT NOT NULL,
is_trivial_plan BIT NOT NULL,
is_parallel_plan BIT NOT NULL,
is_forced_plan BIT NOT NULL,
is_natively_compiled BIT NOT NULL,
force_failure_count BIGINT NOT NULL,
last_force_failure_reason INT NOT NULL,
last_force_failure_reason_desc NVARCHAR(128) NULL,
count_compiles BIGINT NULL,
initial_compile_start_time DATETIMEOFFSET(7) NOT NULL,
last_compile_start_time DATETIMEOFFSET(7) NULL,
last_execution_time DATETIMEOFFSET(7) NULL,
avg_compile_duration_ms FLOAT NULL,
last_compile_duration_ms BIGINT NULL,
plan_forcing_type INT NULL,
plan_forcing_type_desc NVARCHAR(60) NULL
);
/*
Queries and Compile Information
*/
CREATE TABLE #query_store_query
(
query_id BIGINT NOT NULL,
query_text_id BIGINT NOT NULL,
context_settings_id BIGINT NOT NULL,
object_id BIGINT NULL,
object_name AS
ISNULL(
QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id)) + N'.'
+ QUOTENAME(OBJECT_NAME(object_id, database_id)),
N'Adhoc'
),
batch_sql_handle VARBINARY(64) NULL,
query_hash BINARY(8) NOT NULL,
is_internal_query BIT NOT NULL,
query_parameterization_type TINYINT NOT NULL,
query_parameterization_type_desc NVARCHAR(60) NULL,
initial_compile_start_time DATETIMEOFFSET(7) NOT NULL,
last_compile_start_time DATETIMEOFFSET(7) NULL,
last_execution_time DATETIMEOFFSET(7) NULL,
last_compile_batch_sql_handle VARBINARY(64) NULL,
last_compile_batch_offset_start BIGINT NULL,
last_compile_batch_offset_end BIGINT NULL,
count_compiles BIGINT NULL,
avg_compile_duration_ms FLOAT NULL,
total_compile_duration_ms AS (count_compiles * avg_compile_duration_ms),
last_compile_duration_ms BIGINT NULL,
avg_bind_duration_ms FLOAT NULL,
total_bind_duration_ms AS (count_compiles * avg_bind_duration_ms),
last_bind_duration_ms BIGINT NULL,
avg_bind_cpu_time_ms FLOAT NULL,
total_bind_cpu_time_ms AS (count_compiles * avg_bind_cpu_time_ms),
last_bind_cpu_time_ms BIGINT NULL,
avg_optimize_duration_ms FLOAT NULL,
total_optimize_duration_ms AS (count_compiles * avg_optimize_duration_ms),
last_optimize_duration_ms BIGINT NULL,
avg_optimize_cpu_time_ms FLOAT NULL,
total_optimize_cpu_time_ms AS (count_compiles * avg_optimize_cpu_time_ms),
last_optimize_cpu_time_ms BIGINT NULL,
avg_compile_memory_mb FLOAT NULL,
total_compile_memory_mb AS (count_compiles * avg_compile_memory_mb),
last_compile_memory_mb BIGINT NULL,
max_compile_memory_mb BIGINT NULL,
is_clouddb_internal_query BIT NULL,
database_id INT NULL
);
/*
Query Text And Columns From sys.dm_exec_query_stats
*/
CREATE TABLE #query_store_query_text
(
query_text_id BIGINT NOT NULL,
query_sql_text XML NULL,
statement_sql_handle VARBINARY(64) NULL,
is_part_of_encrypted_module BIT NOT NULL,
has_restricted_text BIT NOT NULL,
total_grant_mb BIGINT NULL,
last_grant_mb BIGINT NULL,
min_grant_mb BIGINT NULL,
max_grant_mb BIGINT NULL,
total_used_grant_mb BIGINT NULL,
last_used_grant_mb BIGINT NULL,
min_used_grant_mb BIGINT NULL,
max_used_grant_mb BIGINT NULL,
total_ideal_grant_mb BIGINT NULL,
last_ideal_grant_mb BIGINT NULL,
min_ideal_grant_mb BIGINT NULL,
max_ideal_grant_mb BIGINT NULL,
total_reserved_threads BIGINT NULL,
last_reserved_threads BIGINT NULL,
min_reserved_threads BIGINT NULL,
max_reserved_threads BIGINT NULL,
total_used_threads BIGINT NULL,
last_used_threads BIGINT NULL,
min_used_threads BIGINT NULL,
max_used_threads BIGINT NULL
);
/*
Figure it out.
*/
CREATE TABLE #dm_exec_query_stats
(
statement_sql_handle VARBINARY(64) NOT NULL,
total_grant_mb BIGINT NULL,
last_grant_mb BIGINT NULL,
min_grant_mb BIGINT NULL,
max_grant_mb BIGINT NULL,
total_used_grant_mb BIGINT NULL,
last_used_grant_mb BIGINT NULL,
min_used_grant_mb BIGINT NULL,
max_used_grant_mb BIGINT NULL,
total_ideal_grant_mb BIGINT NULL,
last_ideal_grant_mb BIGINT NULL,
min_ideal_grant_mb BIGINT NULL,
max_ideal_grant_mb BIGINT NULL,
total_reserved_threads BIGINT NULL,
last_reserved_threads BIGINT NULL,
min_reserved_threads BIGINT NULL,
max_reserved_threads BIGINT NULL,
total_used_threads BIGINT NULL,
last_used_threads BIGINT NULL,
min_used_threads BIGINT NULL,
max_used_threads BIGINT NULL
);
/*
Runtime stats information
*/
CREATE TABLE #query_store_runtime_stats
(
runtime_stats_id BIGINT NOT NULL,
plan_id BIGINT NOT NULL,
runtime_stats_interval_id BIGINT NOT NULL,
execution_type_desc NVARCHAR(60) NULL,
first_execution_time DATETIMEOFFSET(7) NOT NULL,
last_execution_time DATETIMEOFFSET(7) NOT NULL,
count_executions BIGINT NOT NULL,
executions_per_second AS
ISNULL(count_executions / NULLIF(DATEDIFF(SECOND, first_execution_time, last_execution_time), 0), 0),
avg_duration_ms FLOAT NULL,
last_duration_ms BIGINT NOT NULL,
min_duration_ms BIGINT NOT NULL,
max_duration_ms BIGINT NOT NULL,
total_duration_ms AS (avg_duration_ms * count_executions),
avg_cpu_time_ms FLOAT NULL,
last_cpu_time_ms BIGINT NOT NULL,
min_cpu_time_ms BIGINT NOT NULL,
max_cpu_time_ms BIGINT NOT NULL,
total_cpu_time_ms AS (avg_cpu_time_ms * count_executions),
avg_logical_io_reads_mb FLOAT NULL,
last_logical_io_reads_mb BIGINT NOT NULL,
min_logical_io_reads_mb BIGINT NOT NULL,
max_logical_io_reads_mb BIGINT NOT NULL,
total_logical_io_reads_mb AS (avg_logical_io_reads_mb * count_executions),
avg_logical_io_writes_mb FLOAT NULL,
last_logical_io_writes_mb BIGINT NOT NULL,
min_logical_io_writes_mb BIGINT NOT NULL,
max_logical_io_writes_mb BIGINT NOT NULL,
total_logical_io_writes_mb AS (avg_logical_io_writes_mb * count_executions),
avg_physical_io_reads_mb FLOAT NULL,
last_physical_io_reads_mb BIGINT NOT NULL,
min_physical_io_reads_mb BIGINT NOT NULL,
max_physical_io_reads_mb BIGINT NOT NULL,
total_physical_io_reads_mb AS (avg_physical_io_reads_mb * count_executions),
avg_clr_time_ms FLOAT NULL,
last_clr_time_ms BIGINT NOT NULL,
min_clr_time_ms BIGINT NOT NULL,
max_clr_time_ms BIGINT NOT NULL,
total_clr_time_ms AS (avg_clr_time_ms * count_executions),
last_dop BIGINT NOT NULL,
min_dop BIGINT NOT NULL,
max_dop BIGINT NOT NULL,
avg_query_max_used_memory_mb FLOAT NULL,
last_query_max_used_memory_mb BIGINT NOT NULL,
min_query_max_used_memory_mb BIGINT NOT NULL,
max_query_max_used_memory_mb BIGINT NOT NULL,
total_query_max_used_memory_mb AS (avg_query_max_used_memory_mb * count_executions),
avg_rowcount FLOAT NULL,
last_rowcount BIGINT NOT NULL,
min_rowcount BIGINT NOT NULL,
max_rowcount BIGINT NOT NULL,
total_rowcount AS (avg_rowcount * count_executions),
avg_num_physical_io_reads_mb FLOAT NULL,
last_num_physical_io_reads_mb BIGINT NULL,
min_num_physical_io_reads_mb BIGINT NULL,
max_num_physical_io_reads_mb BIGINT NULL,
total_num_physical_io_reads_mb AS (avg_num_physical_io_reads_mb * count_executions),
avg_log_bytes_used_mb FLOAT NULL,
last_log_bytes_used_mb BIGINT NULL,
min_log_bytes_used_mb BIGINT NULL,
max_log_bytes_used_mb BIGINT NULL,
total_log_bytes_used_mb AS (avg_log_bytes_used_mb * count_executions),
avg_tempdb_space_used_mb FLOAT NULL,
last_tempdb_space_used_mb BIGINT NULL,
min_tempdb_space_used_mb BIGINT NULL,
max_tempdb_space_used_mb BIGINT NULL,
total_tempdb_space_used_mb AS (avg_tempdb_space_used_mb * count_executions),
context_settings NVARCHAR(256) NULL
);
/*
Wait Stats, When Available
*/
CREATE TABLE #query_store_wait_stats
(
plan_id BIGINT NOT NULL,
wait_category_desc NVARCHAR(60) NOT NULL,
total_query_wait_time_ms BIGINT NOT NULL,
avg_query_wait_time_ms FLOAT NULL,
last_query_wait_time_ms BIGINT NOT NULL,
min_query_wait_time_ms BIGINT NOT NULL,
max_query_wait_time_ms BIGINT NOT NULL
);
/*
Context is everything
*/
CREATE TABLE #query_context_settings
(
context_settings_id BIGINT NOT NULL,
set_options VARBINARY(8) NULL,
language_id SMALLINT NOT NULL,
date_format SMALLINT NOT NULL,
date_first TINYINT NOT NULL,
status VARBINARY(2) NULL,
required_cursor_options INT NOT NULL,
acceptable_cursor_options INT NOT NULL,
merge_action_type SMALLINT NOT NULL,
default_schema_id INT NOT NULL,
is_replication_specific BIT NOT NULL,
is_contained VARBINARY(1) NULL
);
/*
Trouble Loves Me
*/
CREATE TABLE #troubleshoot_performance
(
id BIGINT IDENTITY,
current_table NVARCHAR(100),
start_time DATETIME,
end_time DATETIME,
runtime_ms AS FORMAT(DATEDIFF(MILLISECOND, start_time, end_time), 'N0')
);
/*
Try to be helpful by subbing in a database name if null
*/
IF (
@database_name IS NULL
AND LOWER(DB_NAME()) NOT IN ( N'master', N'model', N'msdb', N'tempdb', N'dbatools', N'dbadmin',
N'dbmaintenance', N'rdsadmin', N'other_memes'
)
)
BEGIN
SELECT @database_name = DB_NAME();
END;
/*
Variables for the variable gods
*/
DECLARE @azure BIT,
@engine INT,
@product_version INT,
@database_id INT,
@database_name_quoted sysname,
@procedure_name_quoted sysname,
@collation sysname,
@new BIT,
@sql NVARCHAR(MAX),
@isolation_level NVARCHAR(MAX),
@parameters NVARCHAR(200),
@plans_top BIGINT,
@nc10 NVARCHAR(2),
@where_clause NVARCHAR(MAX),
@procedure_exists BIT,
@query_store_exists BIT,
@query_store_waits_enabled BIT,
@string_split NVARCHAR(1500),
@current_table NVARCHAR(100),
@troubleshoot_insert NVARCHAR(MAX),
@troubleshoot_update NVARCHAR(MAX),
@troubleshoot_info NVARCHAR(MAX),
@rc BIGINT;
/*
Some variable assignment, because why not?
*/
SELECT @azure = CASE
WHEN CONVERT(sysname, SERVERPROPERTY('EDITION')) = N'SQL Azure' THEN
1
ELSE
0
END,
@engine = CONVERT(INT, SERVERPROPERTY('ENGINEEDITION')),
@product_version = CONVERT(INT, PARSENAME(CONVERT(sysname, SERVERPROPERTY('PRODUCTVERSION')), 4)),
@database_id = DB_ID(@database_name),
@database_name_quoted = QUOTENAME(@database_name),
@procedure_name_quoted
= QUOTENAME(@database_name) + N'.' + QUOTENAME(ISNULL(@procedure_schema, N'dbo')) + N'.'
+ QUOTENAME(@procedure_name),
@collation = CONVERT(sysname, DATABASEPROPERTYEX(@database_name, 'Collation')),
@new = 0,
@sql = N'',
@isolation_level = N'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;',
@parameters
= N'@top bigint,
@start_date datetime,
@end_date datetime,
@execution_count bigint,
@duration_ms bigint',
@plans_top = CASE
WHEN @include_plan_ids IS NULL THEN
1
ELSE
10
END,
@nc10 = NCHAR(10),
@where_clause = N'',
@procedure_exists = 0,
@query_store_exists = 0,
@query_store_waits_enabled = 0,
@current_table = N'',
@string_split
= N'
SELECT DISTINCT
LTRIM
(
RTRIM
(
ids.ids
)
) AS ids
FROM
(
SELECT
ids =
x.x.value
(
''(./text())[1]'',
''bigint''
)
FROM
(
SELECT
ids =
CONVERT
(
xml,
''<x>'' +
REPLACE
(
REPLACE
(
@ids,
'','',
''</x><x>''
),
'' '',
''''
) +
''</x>''
).query(''.'')
) AS ids
CROSS APPLY ids.nodes(''x'') AS x (x)
) AS ids
OPTION(RECOMPILE);',
@troubleshoot_insert
= N'
INSERT
#troubleshoot_performance WITH(TABLOCK)
(
current_table,
start_time
)
VALUES
(
@current_table,
GETDATE()
)
OPTION(RECOMPILE);',
@troubleshoot_update
= N'
UPDATE tp
SET tp.end_time = GETDATE()
FROM #troubleshoot_performance AS tp
WHERE tp.current_table = @current_table
OPTION(RECOMPILE);',
@troubleshoot_info
= N'
SELECT
(
SELECT
runtime_ms =
tp.runtime_ms,
current_table =
tp.current_table,
query_length =
FORMAT(LEN(@sql), ''N0''),
''processing-instruction(statement_text)'' =
@sql
FROM #troubleshoot_performance AS tp
WHERE tp.current_table = @current_table
FOR XML PATH(N''''), TYPE
).query(''.[1]'') AS current_query
OPTION(RECOMPILE);',
@rc = 0;
/*
Some parameters can't be NULL,
and some shouldn't be empty strings
*/
SELECT @sort_order = ISNULL(@sort_order, 'cpu'),
@top = ISNULL(@top, 10),
@expert_mode = ISNULL(@expert_mode, 0),
@procedure_schema = NULLIF(@procedure_schema, ''),
@procedure_name = NULLIF(@procedure_name, ''),
@include_plan_ids = NULLIF(@include_plan_ids, ''),
@include_query_ids = NULLIF(@include_query_ids, ''),
@ignore_plan_ids = NULLIF(@ignore_plan_ids, ''),
@ignore_query_ids = NULLIF(@ignore_query_ids, ''),
@wait_filter = NULLIF(@wait_filter, ''),
@format_output = ISNULL(@format_output, 0),
@help = ISNULL(@help, 0),
@debug = ISNULL(@debug, 0),
@troubleshoot_performance = ISNULL(@troubleshoot_performance, 0);
/*
Let's make sure things will work
*/
/*
Database are you there?
*/
IF (@database_id IS NULL OR @collation IS NULL)
BEGIN
RAISERROR('Database %s does not exist', 11, 1, @database_name) WITH NOWAIT;
RETURN;
END;
/*
Database what are you?
*/
IF (@azure = 1 AND @engine NOT IN ( 5, 8 ))
BEGIN
RAISERROR('Not all Azure offerings are supported, please try avoiding memes', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Database are you compatible?
*/
IF (
@azure = 1
AND EXISTS
(
SELECT 1 / 0
FROM sys.databases AS d
WHERE d.database_id = @database_id
AND d.compatibility_level < 130
)
)
BEGIN
RAISERROR('Azure databases in compatiblity levels under 130 are not supported', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Sometimes sys.databases will report Query Store being on, but it's really not
*/
SELECT @current_table = N'checking query store existence',
@sql = @isolation_level;
IF @troubleshoot_performance = 1
BEGIN
EXEC sys.sp_executesql @troubleshoot_insert,
N'@current_table nvarchar(100)',
@current_table;
SET STATISTICS XML ON;
END;
SELECT @sql += N'
SELECT
@query_store_exists =
CASE
WHEN EXISTS
(
SELECT