-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_PressureDetector.sql
More file actions
4515 lines (4288 loc) · 165 KB
/
sp_PressureDetector.sql
File metadata and controls
4515 lines (4288 loc) · 165 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_PressureDetector
@help = 1;
For working through errors:
EXECUTE sp_PressureDetector
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID(N'dbo.sp_PressureDetector', N'P') IS NULL
EXECUTE (N'CREATE PROCEDURE dbo.sp_PressureDetector AS RETURN 138;');
GO
ALTER PROCEDURE
dbo.sp_PressureDetector
(
@what_to_check varchar(6) = 'all', /*areas to check for pressure*/
@skip_queries bit = 0, /*if you want to skip looking at running queries*/
@skip_plan_xml bit = 0, /*if you want to skip getting plan XML*/
@minimum_disk_latency_ms smallint = 100, /*low bound for reporting disk latency*/
@cpu_utilization_threshold smallint = 50, /*low bound for reporting high cpu utlization*/
@skip_waits bit = 0, /*skips waits when you do not need them on every run*/
@skip_perfmon bit = 0, /*skips perfmon counters when you do not need them on every run*/
@sample_seconds tinyint = 0, /*take a sample of your server's metrics*/
@log_to_table bit = 0, /*enable logging to permanent tables*/
@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 = 'PressureDetector', /*prefix for all logging tables*/
@log_retention_days integer = 30, /*Number of days to keep logs, 0 = keep indefinitely*/
@help bit = 0, /*how you got here*/
@troubleshoot_blocking bit = 0, /*show blocking chains instead of pressure analysis*/
@debug bit = 0, /*prints dynamic sql, displays parameter and variable values, and table contents*/
@version varchar(5) = 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 ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET LANGUAGE us_english;
SELECT
@version = '6.4',
@version_date = '20260401';
IF @help = 1
BEGIN
/*
Introduction
*/
SELECT
introduction =
'hi, i''m sp_PressureDetector!' UNION ALL
SELECT 'you got me from https://code.erikdarling.com' UNION ALL
SELECT 'i''m a lightweight tool for monitoring cpu and memory pressure' UNION ALL
SELECT 'i''ll tell you: ' UNION ALL
SELECT ' * what''s currently consuming memory on your server' UNION ALL
SELECT ' * wait stats relevant to cpu, memory, and disk pressure, along with query performance' UNION ALL
SELECT ' * how many worker threads and how much memory you have available' UNION ALL
SELECT ' * running queries that are using cpu and memory' UNION ALL
SELECT 'from https://erikdarling.com';
/*
Parameters
*/
SELECT
parameter_name =
ap.name,
data_type = t.name,
description =
CASE
ap.name
WHEN N'@what_to_check' THEN N'areas to check for pressure'
WHEN N'@skip_queries' THEN N'if you want to skip looking at running queries'
WHEN N'@skip_plan_xml' THEN N'if you want to skip getting plan XML'
WHEN N'@minimum_disk_latency_ms' THEN N'low bound for reporting disk latency'
WHEN N'@cpu_utilization_threshold' THEN N'low bound for reporting high cpu utlization'
WHEN N'@skip_waits' THEN N'skips waits when you do not need them on every run'
WHEN N'@skip_perfmon' THEN N'skips perfmon counters when you do not need them on every run'
WHEN N'@sample_seconds' THEN N'take a sample of your server''s metrics'
WHEN N'@log_to_table' THEN N'enable logging to permanent tables instead of returning results'
WHEN N'@log_database_name' THEN N'database to store logging tables'
WHEN N'@log_schema_name' THEN N'schema to store logging tables'
WHEN N'@log_table_name_prefix' THEN N'prefix for all logging tables'
WHEN N'@log_retention_days' THEN N'how many days of data to retain'
WHEN N'@help' THEN N'how you got here'
WHEN N'@troubleshoot_blocking' THEN N'show blocking chains instead of pressure analysis'
WHEN N'@debug' THEN N'prints dynamic sql, displays parameter and variable values, and table contents'
WHEN N'@version' THEN N'OUTPUT; for support'
WHEN N'@version_date' THEN N'OUTPUT; for support'
END,
valid_inputs =
CASE
ap.name
WHEN N'@what_to_check' THEN N'"all", "cpu", and "memory"'
WHEN N'@skip_queries' THEN N'0 or 1'
WHEN N'@skip_plan_xml' THEN N'0 or 1'
WHEN N'@minimum_disk_latency_ms' THEN N'a reasonable number of milliseconds for disk latency'
WHEN N'@cpu_utilization_threshold' THEN N'a reasonable cpu utlization percentage'
WHEN N'@skip_waits' THEN N'0 or 1'
WHEN N'@skip_perfmon' THEN N'0 or 1'
WHEN N'@sample_seconds' THEN N'a valid tinyint: 0-255'
WHEN N'@log_to_table' THEN N'0 or 1'
WHEN N'@log_database_name' THEN N'any valid database name'
WHEN N'@log_schema_name' THEN N'any valid schema name'
WHEN N'@log_table_name_prefix' THEN N'any valid identifier'
WHEN N'@log_retention_days' THEN N'a positive integer'
WHEN N'@help' THEN N'0 or 1'
WHEN N'@troubleshoot_blocking' THEN N'0 or 1'
WHEN N'@debug' THEN N'0 or 1'
WHEN N'@version' THEN N'none'
WHEN N'@version_date' THEN N'none'
END,
defaults =
CASE
ap.name
WHEN N'@what_to_check' THEN N'all'
WHEN N'@skip_queries' THEN N'0'
WHEN N'@skip_plan_xml' THEN N'0'
WHEN N'@minimum_disk_latency_ms' THEN N'100'
WHEN N'@cpu_utilization_threshold' THEN N'50'
WHEN N'@skip_waits' THEN N'0'
WHEN N'@skip_perfmon' THEN N'0'
WHEN N'@sample_seconds' THEN N'0'
WHEN N'@log_to_table' THEN N'0'
WHEN N'@log_database_name' THEN N'NULL (current database)'
WHEN N'@log_schema_name' THEN N'NULL (dbo)'
WHEN N'@log_table_name_prefix' THEN N'PressureDetector'
WHEN N'@log_retention_days' THEN N'30'
WHEN N'@help' THEN N'0'
WHEN N'@troubleshoot_blocking' THEN N'0'
WHEN N'@debug' THEN N'0'
WHEN N'@version' THEN N'none; OUTPUT'
WHEN N'@version_date' THEN N'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_PressureDetector'
OPTION(MAXDOP 1, RECOMPILE);
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*/
/*
If @troubleshoot_blocking = 1, skip all other analysis and go directly to blocking analysis
*/
IF @troubleshoot_blocking = 1
BEGIN
GOTO troubleshoot_blocking;
END;
/*
Fix parameters and check the values, etc.
*/
SELECT
@what_to_check = ISNULL(@what_to_check, 'all'),
@skip_queries = ISNULL(@skip_queries, 0),
@skip_plan_xml = ISNULL(@skip_plan_xml, 0),
@minimum_disk_latency_ms = ISNULL(@minimum_disk_latency_ms, 100),
@cpu_utilization_threshold = ISNULL(@cpu_utilization_threshold, 50),
@skip_waits = ISNULL(@skip_waits, 0),
@skip_perfmon = ISNULL(@skip_perfmon, 0),
@sample_seconds = ISNULL(@sample_seconds, 0),
@log_to_table = ISNULL(@log_to_table, 0),
@troubleshoot_blocking = ISNULL(@troubleshoot_blocking, 0),
@help = ISNULL(@help, 0),
@debug = ISNULL(@debug, 0);
SELECT
@what_to_check = LOWER(@what_to_check);
IF @what_to_check NOT IN ('cpu', 'memory', 'all')
BEGIN
RAISERROR('@what_to_check was set to %s, setting to all', 0, 1, @what_to_check) WITH NOWAIT;
SELECT
@what_to_check = 'all';
END;
IF @log_to_table = 1
AND @cpu_utilization_threshold > 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Setting @cpu_utilization_threshold to 0 to capture all CPU utilization data when logging to tables', 0, 1) WITH NOWAIT;
END;
SELECT
@cpu_utilization_threshold = 0;
END;
IF @log_to_table = 1
AND @sample_seconds <> 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Logging to tables is not compatible with @sample_seconds. Using @sample_seconds = 0', 0, 1) WITH NOWAIT;
END;
SELECT
@sample_seconds = 0;
END;
IF @log_to_table = 1
AND @what_to_check <> 'all'
BEGIN
IF @debug = 1
BEGIN
RAISERROR('@what_to_check was set to %s, setting to all when logging to tables', 0, 1, @what_to_check) WITH NOWAIT;
END;
SELECT
@what_to_check = 'all';
END;
IF @log_to_table = 1
AND
(
@skip_queries = 1
OR @skip_plan_xml = 1
OR @skip_waits = 1
OR @skip_perfmon = 1
)
BEGIN
IF @debug = 1
BEGIN
RAISERROR('reverting skip options for table logging', 0, 1, @what_to_check) WITH NOWAIT;
END;
SELECT
@skip_queries = 0,
@skip_plan_xml = 0,
@skip_waits = 0,
@skip_perfmon = 0;
END;
/*
Declarations of Variablependence
*/
IF @debug = 1
BEGIN
RAISERROR('Declaring variables and temporary tables', 0, 1) WITH NOWAIT;
END;
DECLARE
@azure bit =
CASE
WHEN
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 5
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@pool_sql nvarchar(max) = N'',
@pages_kb bit =
CASE
WHEN
(
SELECT
COUNT_BIG(*)
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_os_memory_clerks')
AND ac.name = N'pages_kb'
) = 1
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@mem_sql nvarchar(max) = N'',
@helpful_new_columns bit =
CASE
WHEN
(
SELECT
COUNT_BIG(*)
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_exec_query_memory_grants')
AND ac.name IN
(
N'reserved_worker_count',
N'used_worker_count'
)
) = 2
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@cpu_sql nvarchar(max) = N'',
@cool_new_columns bit =
CASE
WHEN
(
SELECT
COUNT_BIG(*)
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.dm_exec_requests')
AND ac.name IN
(
N'dop',
N'parallel_worker_count'
)
) = 2
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@reserved_worker_count_out varchar(10) = '0',
@reserved_worker_count nvarchar(max) = N'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@reserved_worker_count_out =
SUM(deqmg.reserved_worker_count)
FROM sys.dm_exec_query_memory_grants AS deqmg
OPTION(MAXDOP 1, RECOMPILE);
',
@cpu_details nvarchar(max) = N'',
@cpu_details_output xml = N'',
@cpu_details_columns nvarchar(max) = N'',
@cpu_details_select nvarchar(max) = N'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@cpu_details_output =
(
SELECT
offline_cpus =
(SELECT COUNT_BIG(*) FROM sys.dm_os_schedulers dos WHERE dos.is_online = 0),
',
@cpu_details_from nvarchar(max) = N'
FROM sys.dm_os_sys_info AS osi
FOR XML
PATH(''cpu_details''),
TYPE
)
OPTION(MAXDOP 1, RECOMPILE);',
@database_size_out nvarchar(max) = N'',
@database_size_out_gb nvarchar(10) = '0',
@total_physical_memory_gb bigint,
@cpu_utilization xml = N'',
@low_memory xml = N'',
@health_history bit =
CASE
WHEN OBJECT_ID('sys.dm_os_memory_health_history') IS NOT NULL
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@health_history_xml xml,
@disk_check nvarchar(max) = N'',
@live_plans bit =
CASE
WHEN OBJECT_ID('sys.dm_exec_query_statistics_xml') IS NOT NULL
THEN CONVERT(bit, 'true')
ELSE CONVERT(bit, 'false')
END,
@waitfor varchar(20) =
CONVERT
(
nvarchar(20),
DATEADD
(
SECOND,
@sample_seconds,
'19000101'
),
114
),
@pass tinyint =
CASE @sample_seconds
WHEN 0
THEN 1
ELSE 0
END,
@prefix sysname =
ISNULL
(
(
SELECT TOP (1)
SUBSTRING
(
dopc.object_name,
1,
CHARINDEX(N':', dopc.object_name)
)
FROM sys.dm_os_performance_counters AS dopc
) +
N'%',
N'%'
),
@memory_grant_cap xml,
@cache_xml xml,
@cache_sql nvarchar(max) = N'',
@resource_semaphores nvarchar(max) = N'',
@cpu_threads nvarchar(max) = N'',
/*Log to table stuff*/
@log_table_waits sysname,
@log_table_file_metrics sysname,
@log_table_perfmon sysname,
@log_table_memory sysname,
@log_table_cpu sysname,
@log_table_memory_consumers sysname,
@log_table_memory_queries sysname,
@log_table_cpu_queries sysname,
@log_table_cpu_events sysname,
@cleanup_date datetime2(7),
@max_sample_time datetime,
@check_sql nvarchar(max) = N'',
@create_sql nvarchar(max) = N'',
@insert_sql nvarchar(max) = N'',
@delete_sql nvarchar(max) = N'',
@log_database_schema nvarchar(1024);
/* Validate logging parameters */
IF @log_to_table = 1
BEGIN
SELECT
/* Default database name to current database if not specified */
@log_database_name = ISNULL(@log_database_name, DB_NAME()),
/* Default schema name to dbo if not specified */
@log_schema_name = ISNULL(@log_schema_name, N'dbo');
/* Validate database exists */
IF NOT EXISTS
(
SELECT
1/0
FROM sys.databases AS d
WHERE d.name = @log_database_name
)
BEGIN
RAISERROR('The specified logging database %s does not exist. Logging will be disabled.', 11, 1, @log_database_name) WITH NOWAIT;
RETURN;
END;
SELECT
@log_database_schema =
QUOTENAME(@log_database_name) +
N'.' +
QUOTENAME(@log_schema_name) +
N'.';
/* Generate fully qualified table names */
SELECT
@log_table_waits =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_Waits'),
@log_table_file_metrics =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_FileMetrics'),
@log_table_perfmon =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_Perfmon'),
@log_table_memory =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_Memory'),
@log_table_cpu =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_CPU'),
@log_table_memory_consumers =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_MemoryConsumers'),
@log_table_memory_queries =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_MemoryQueries'),
@log_table_cpu_queries =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_CPUQueries'),
@log_table_cpu_events =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_CPUEvents');
/* Check if schema exists and create it if needed */
SET @check_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
WHERE s.name = @schema_name
)
BEGIN
DECLARE
@create_schema_sql nvarchar(max) = N''CREATE SCHEMA '' + QUOTENAME(@schema_name);
EXECUTE ' + QUOTENAME(@log_database_name) + N'.sys.sp_executesql @create_schema_sql;
IF @debug = 1 BEGIN RAISERROR(''Created schema %s in database %s for logging.'', 0, 1, @schema_name, @db_name) WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@check_sql,
N'@schema_name sysname,
@db_name sysname,
@debug bit',
@log_schema_name,
@log_database_name,
@debug;
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_Waits''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_waits + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
server_hours_uptime integer NULL,
server_hours_cpu_time decimal(38,2) NULL,
wait_type nvarchar(60) NOT NULL,
description nvarchar(60) NULL,
hours_wait_time decimal(38,2) NULL,
avg_ms_per_wait decimal(38,2) NULL,
percent_signal_waits decimal(38,2) NULL,
waiting_tasks_count bigint NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for wait stats logging.'', 0, 1, ''' + @log_table_waits + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_FileMetrics''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_file_metrics + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
server_hours_uptime integer NULL,
drive nvarchar(255) NOT NULL,
database_name nvarchar(128) NOT NULL,
database_file_details nvarchar(1000) NULL,
file_size_gb decimal(38,2) NULL,
total_gb_read decimal(38,2) NULL,
total_mb_read decimal(38,2) NULL,
total_read_count bigint NULL,
avg_read_stall_ms decimal(38,2) NULL,
total_gb_written decimal(38,2) NULL,
total_mb_written decimal(38,2) NULL,
total_write_count bigint NULL,
avg_write_stall_ms decimal(38,2) NULL,
io_stall_read_ms bigint NULL,
io_stall_write_ms bigint NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for file metrics logging.'', 0, 1, ''' + @log_table_file_metrics + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_Perfmon''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_perfmon + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
object_name sysname NOT NULL,
counter_name sysname NOT NULL,
counter_name_clean sysname NULL,
instance_name sysname NOT NULL,
cntr_value bigint NULL,
cntr_type bigint NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for perfmon logging.'', 0, 1, ''' + @log_table_perfmon + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_Memory''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
resource_semaphore_id integer NOT NULL,
total_database_size_gb varchar(20) NULL,
total_physical_memory_gb bigint NULL,
max_server_memory_gb bigint NULL,
max_memory_grant_cap xml NULL,
memory_model nvarchar(128) NULL,
target_memory_gb decimal(38,2) NULL,
max_target_memory_gb decimal(38,2) NULL,
total_memory_gb decimal(38,2) NULL,
available_memory_gb decimal(38,2) NULL,
granted_memory_gb decimal(38,2) NULL,
used_memory_gb decimal(38,2) NULL,
grantee_count integer NULL,
waiter_count integer NULL,
timeout_error_count integer NULL,
forced_grant_count integer NULL,
total_reduced_memory_grant_count bigint NULL,
pool_id integer NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory logging.'', 0, 1, ''' + @log_table_memory + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_CPU''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_cpu + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
total_threads integer NULL,
used_threads integer NULL,
available_threads integer NULL,
reserved_worker_count varchar(10) NULL,
threads_waiting_for_cpu integer NULL,
requests_waiting_for_threads integer NULL,
current_workers integer NULL,
total_active_request_count integer NULL,
total_queued_request_count integer NULL,
total_blocked_task_count integer NULL,
total_active_parallel_thread_count integer NULL,
avg_runnable_tasks_count float NULL,
high_runnable_percent varchar(100) NULL,
cpu_details_output xml NULL,
cpu_utilization_over_threshold xml NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for CPU logging.'', 0, 1, ''' + @log_table_cpu + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
/* Memory Consumers table */
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_MemoryConsumers''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory_consumers + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
memory_source nvarchar(128) NOT NULL,
memory_consumer nvarchar(128) NOT NULL,
memory_consumed_gb decimal(38,2) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory consumers logging.'', 0, 1, ''' + @log_database_schema + QUOTENAME(@log_table_name_prefix + N'_MemoryConsumers') + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
/* Memory Query Grants table */
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_MemoryQueries''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory_queries + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
session_id integer NOT NULL,
database_name nvarchar(128) NULL,
duration varchar(30) NULL,
request_time datetime NULL,
grant_time datetime NULL,
wait_time_seconds decimal(38,2) NULL,
requested_memory_gb decimal(38,2) NULL,
granted_memory_gb decimal(38,2) NULL,
used_memory_gb decimal(38,2) NULL,
max_used_memory_gb decimal(38,2) NULL,
ideal_memory_gb decimal(38,2) NULL,
required_memory_gb decimal(38,2) NULL,
queue_id integer NULL,
wait_order integer NULL,
is_next_candidate bit NULL,
wait_type nvarchar(60) NULL,
wait_duration_seconds decimal(38,2) NULL,
dop integer NULL,
reserved_worker_count integer NULL,
used_worker_count integer NULL,
plan_handle varbinary(64) NULL,
sql_text xml NULL,
query_plan_xml xml NULL,
live_query_plan xml NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory queries logging.'', 0, 1, ''' + @log_database_schema + QUOTENAME(@log_table_name_prefix + N'_MemoryQueries') + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
/* CPU Queries table */
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_CPUQueries''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_cpu_queries + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
session_id integer NOT NULL,
database_name nvarchar(128) NULL,
duration varchar(30) NULL,
status nvarchar(30) NULL,
blocking_session_id integer NULL,
wait_type nvarchar(60) NULL,
wait_time_ms bigint NULL,
wait_resource nvarchar(512) NULL,
cpu_time_ms bigint NULL,
total_elapsed_time_ms bigint NULL,
reads bigint NULL,
writes bigint NULL,
logical_reads bigint NULL,
granted_query_memory_gb decimal(38,2) NULL,
transaction_isolation_level sysname NULL,
dop integer NULL,
parallel_worker_count integer NULL,
plan_handle varbinary(64) NULL,
sql_text xml NULL,
query_plan_xml xml NULL,
live_query_plan xml NULL,
statement_start_offset integer NULL,
statement_end_offset integer NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for CPU queries logging.'', 0, 1, ''' + @log_database_schema + QUOTENAME(@log_table_name_prefix + N'_CPUQueries') + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
/* CPU Utilization Events table */
SET @create_sql = N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@log_database_name) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@log_database_name) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table_name + N''_CPUEvents''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_cpu_events + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
sample_time datetime NULL,
sqlserver_cpu_utilization integer NULL,
other_process_cpu_utilization integer NULL,
total_cpu_utilization integer NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for CPU utilization events logging.'', 0, 1, ''' + @log_database_schema + QUOTENAME(@log_table_name_prefix + N'_CPUEvents') + N''') WITH NOWAIT; END;
END';
EXECUTE sys.sp_executesql
@create_sql,
N'@schema_name sysname,
@table_name sysname,
@debug bit',
@log_schema_name,
@log_table_name_prefix,
@debug;
/* Handle log retention if specified */
IF @log_to_table = 1 AND @log_retention_days > 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Cleaning up log tables older than %i days', 0, 1, @log_retention_days) WITH NOWAIT;
END;
SET @cleanup_date =
DATEADD
(
DAY,
-@log_retention_days,
SYSDATETIME()
);
/* Clean up each log table */
SET @delete_sql = N'
DELETE FROM ' + @log_table_waits + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_file_metrics + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_perfmon + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_memory + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_cpu + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_memory_consumers + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_memory_queries + '
WHERE collection_time < @cleanup_date;
DELETE FROM ' + @log_table_cpu_queries + '
WHERE collection_time < @cleanup_date;