-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_HealthParser.sql
More file actions
6275 lines (5874 loc) · 231 KB
/
sp_HealthParser.sql
File metadata and controls
6275 lines (5874 loc) · 231 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 support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID(N'dbo.sp_HealthParser', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_HealthParser AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_HealthParser
(
@what_to_check varchar(10) = 'all', /*Specify which portion of the data to check*/
@start_date datetimeoffset(7) = NULL, /*Begin date for events*/
@end_date datetimeoffset(7) = NULL, /*End date for events*/
@warnings_only bit = 0, /*Only show results from recorded warnings*/
@database_name sysname = NULL, /*Filter to a specific database for blocking)*/
@wait_duration_ms bigint = 500, /*Minimum duration to show query waits*/
@wait_round_interval_minutes bigint = 60, /*Nearest interval to round wait stats to*/
@skip_locks bit = 0, /*Skip the blocking and deadlocks*/
@skip_waits bit = 0, /*Skip the wait stats*/
@use_ring_buffer bit = 0, /*Use ring_buffer target instead of file target for system_health session*/
@pending_task_threshold integer = 10, /*Minimum number of pending tasks to care about*/
@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 = 'HealthParser', /*prefix for all logging tables*/
@log_retention_days integer = 30, /*Number of days to keep logs, 0 = keep indefinitely*/
@debug bit = 0, /*Select from temp tables to get event data in raw xml*/
@help bit = 0, /*Get help*/
@version varchar(30) = NULL OUTPUT, /*Script version*/
@version_date datetime = NULL OUTPUT /*Script date*/
)
WITH
RECOMPILE
AS
BEGIN
SET STATISTICS XML OFF;
SET NOCOUNT ON;
SET XACT_ABORT OFF;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@version = '3.6',
@version_date = '20260501';
IF @help = 1
BEGIN
SELECT
introduction =
'hi, i''m sp_HealthParser!' UNION ALL
SELECT 'you can use me to examine the contents of the system_health extended event session' UNION ALL
SELECT 'i apologize if i take a long time, i have to do a lot of XML processing' UNION ALL
SELECT 'from your loving sql server consultant, erik darling: erikdarling.com';
/*
Parameters
*/
SELECT
parameter_name =
ap.name,
data_type =
t.name,
description =
CASE
ap.name
WHEN N'@what_to_check' THEN N'areas of system health to check'
WHEN N'@start_date' THEN N'earliest date to show data for, will be internally converted to UTC'
WHEN N'@end_date' THEN N'latest date to show data for, will be internally converted to UTC'
WHEN N'@warnings_only' THEN N'only show rows where a warning was reported'
WHEN N'@database_name' THEN N'database name to show blocking events for'
WHEN N'@wait_duration_ms' THEN N'minimum wait duration'
WHEN N'@wait_round_interval_minutes' THEN N'interval to round minutes to for wait stats'
WHEN N'@skip_locks' THEN N'skip the blocking and deadlocking section'
WHEN N'@skip_waits' THEN N'skip the wait stats section'
WHEN N'@use_ring_buffer' THEN N'use ring_buffer target instead of file target for faster collection'
WHEN N'@pending_task_threshold' THEN N'minimum number of pending tasks to display'
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'@version' THEN N'OUTPUT; for support'
WHEN N'@version_date' THEN N'OUTPUT; for support'
WHEN N'@help' THEN N'how you got here'
WHEN N'@debug' THEN N'prints dynamic sql, selects from temp tables'
END,
valid_inputs =
CASE
ap.name
WHEN N'@what_to_check' THEN N'all, waits, disk, cpu, memory, system, locking'
WHEN N'@start_date' THEN N'a reasonable date'
WHEN N'@end_date' THEN N'a reasonable date'
WHEN N'@warnings_only' THEN N'NULL, 0, 1'
WHEN N'@database_name' THEN N'the name of a database'
WHEN N'@wait_duration_ms' THEN N'the minimum duration of a wait for queries with interesting waits'
WHEN N'@wait_round_interval_minutes' THEN N'interval to round minutes to for top wait stats by count and duration'
WHEN N'@skip_locks' THEN N'0 or 1'
WHEN N'@skip_waits' THEN N'0 or 1'
WHEN N'@use_ring_buffer' THEN N'0 or 1'
WHEN N'@pending_task_threshold' THEN N'a valid integer'
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'@version' THEN N'none'
WHEN N'@version_date' THEN N'none'
WHEN N'@help' THEN N'0 or 1'
WHEN N'@debug' THEN N'0 or 1'
END,
defaults =
CASE
ap.name
WHEN N'@what_to_check' THEN N'all'
WHEN N'@start_date' THEN N'seven days back'
WHEN N'@end_date' THEN N'current date'
WHEN N'@warnings_only' THEN N'0'
WHEN N'@database_name' THEN N'NULL'
WHEN N'@wait_duration_ms' THEN N'500'
WHEN N'@wait_round_interval_minutes' THEN N'60'
WHEN N'@skip_locks' THEN N'0'
WHEN N'@skip_waits' THEN N'0'
WHEN N'@use_ring_buffer' THEN N'0'
WHEN N'@pending_task_threshold' THEN N'10'
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'HealthParser'
WHEN N'@log_retention_days' THEN N'30'
WHEN N'@version' THEN N'none; OUTPUT'
WHEN N'@version_date' THEN N'none; OUTPUT'
WHEN N'@help' THEN N'0'
WHEN N'@debug' THEN N'0'
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_HealthParser'
ORDER BY
ap.parameter_id
OPTION(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, 0) WITH NOWAIT;
RETURN;
END; /*End help section*/
IF @debug = 1
BEGIN
RAISERROR('Declaring variables', 0, 0) WITH NOWAIT;
END;
DECLARE
@sql nvarchar(MAX) =
N'',
@params nvarchar(MAX) =
N'@start_date datetimeoffset(7),
@end_date datetimeoffset(7)',
@azure bit =
CASE
WHEN
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 5
THEN 1
ELSE 0
END,
@azure_msg nchar(1),
@mi bit =
CASE
WHEN
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 8
THEN 1
ELSE 0
END,
@mi_msg nchar(1),
@dbid integer =
DB_ID(@database_name),
@timestamp_utc_mode tinyint,
@sql_template nvarchar(MAX) = N'',
@time_filter nvarchar(MAX) = N'',
@cross_apply nvarchar(MAX) = N'',
@collection_cursor CURSOR,
@area_name varchar(20),
@object_name sysname,
@temp_table sysname,
@insert_list sysname,
@collection_sql nvarchar(MAX),
/*Log to table stuff*/
@log_table_significant_waits sysname,
@log_table_waits_by_count sysname,
@log_table_waits_by_duration sysname,
@log_table_io_issues sysname,
@log_table_cpu_tasks sysname,
@log_table_memory_conditions sysname,
@log_table_memory_broker sysname,
@log_table_memory_node_oom sysname,
@log_table_system_health sysname,
@log_table_scheduler_issues sysname,
@log_table_severe_errors sysname,
@log_table_pending_tasks sysname,
@log_table_blocking sysname,
@log_table_deadlocks sysname,
@cleanup_date datetime2(7),
@check_sql nvarchar(MAX) = N'',
@create_sql nvarchar(MAX) = N'',
@insert_sql nvarchar(MAX) = N'',
@log_database_schema nvarchar(1024),
@max_event_time datetime2(7),
@dsql nvarchar(MAX) = N'',
@mdsql_template nvarchar(MAX) = N'',
@mdsql_execute nvarchar(MAX) = N'',
@start_date_debug nvarchar(50),
@end_date_debug nvarchar(50);
IF @azure = 1
BEGIN
RAISERROR('This won''t work in Azure because it''s horrible', 11, 1) WITH NOWAIT;
RETURN;
END;
IF @debug = 1
BEGIN
RAISERROR('Fixing parameters and variables', 0, 0) WITH NOWAIT;
END;
/*
Normalize dates to UTC offset for comparison with system_health events
When dates are NULL, use SYSUTCDATETIME() which is already UTC
When dates are provided, SWITCHOFFSET converts from any timezone to UTC
This matches sp_QuickieStore pattern for handling date conversions
*/
SELECT
@start_date =
ISNULL
(
SWITCHOFFSET
(
@start_date,
'+00:00'
),
DATEADD
(
DAY,
-7,
SYSUTCDATETIME()
)
),
@end_date =
ISNULL
(
SWITCHOFFSET
(
@end_date,
'+00:00'
),
SYSUTCDATETIME()
),
@wait_round_interval_minutes = /*do this i guess?*/
CASE
WHEN @wait_round_interval_minutes < 1
THEN 1
ELSE @wait_round_interval_minutes
END,
@azure_msg =
CONVERT(nchar(1), @azure),
@mi_msg =
CONVERT(nchar(1), @mi),
@timestamp_utc_mode =
CASE
WHEN EXISTS
(
SELECT
1/0
FROM sys.all_columns AS ac
WHERE ac.object_id = OBJECT_ID(N'sys.fn_xe_file_target_read_file')
AND ac.name = N'timestamp_utc'
)
THEN 1 +
CASE
WHEN
PARSENAME
(
CONVERT
(
sysname,
SERVERPROPERTY('PRODUCTVERSION')
),
4
) > 16
THEN 1
ELSE 0
END +
CASE
WHEN @mi = 1
THEN 1
ELSE 0
END
ELSE 0
END,
@sql_template += N'
INSERT INTO
{temp_table}
WITH
(TABLOCK)
(
{insert_list}
)
SELECT
{object_name} =
ISNULL
(
xml.{object_name},
CONVERT(xml, N''<event>event</event>'')
)
FROM
(
SELECT
{object_name} =
TRY_CAST(fx.event_data AS xml)
FROM sys.fn_xe_file_target_read_file(N''system_health*.xel'', NULL, NULL, NULL) AS fx
WHERE fx.object_name = N''{object_name}'' {time_filter}
) AS xml
{cross_apply}
OPTION(RECOMPILE);
',
@mdsql_template = N'
IF OBJECT_ID(''{table_check}'', ''U'') IS NOT NULL
BEGIN
SELECT
@max_event_time =
ISNULL
(
MAX({date_column}),
DATEADD
(
MINUTE,
DATEDIFF
(
MINUTE,
SYSDATETIME(),
GETUTCDATE()
),
DATEADD
(
DAY,
-1,
SYSDATETIME()
)
)
)
FROM {table_check};
END;
';
SELECT
@start_date_debug = @start_date,
@end_date_debug = @end_date;
IF @timestamp_utc_mode = 0
BEGIN
/* Pre-2017 handling */
SET @time_filter = N'';
SET @cross_apply = N'CROSS APPLY xml.{object_name}.nodes(''/event'') AS e(x)
CROSS APPLY (SELECT x.value( ''(@timestamp)[1]'', ''datetimeoffset'' )) ca ([utc_timestamp])
WHERE ca.utc_timestamp >= @start_date
AND ca.utc_timestamp < @end_date';
END;
ELSE
BEGIN
/*
2017+ handling. Use the same half-open (>= @start_date AND
< @end_date) shape as the pre-2017 branch so an event captured
at exactly @end_date is not included on 2017+ while excluded
on pre-2017 — previously BETWEEN meant a closed interval on
2017+ and a row at the boundary could appear or not depending
on which branch ran.
*/
SET @cross_apply = N'CROSS APPLY xml.{object_name}.nodes(''/event'') AS e(x)';
IF @timestamp_utc_mode = 1
SET @time_filter = N'
AND CONVERT(datetimeoffset(7), fx.timestamp_utc) >= @start_date
AND CONVERT(datetimeoffset(7), fx.timestamp_utc) < @end_date';
ELSE
SET @time_filter = N'
AND fx.timestamp_utc >= @start_date
AND fx.timestamp_utc < @end_date';
END;
SET @sql_template =
REPLACE
(
REPLACE
(
@sql_template,
'{time_filter}',
@time_filter
),
'{cross_apply}',
@cross_apply
);
/*If any parameters that expect non-NULL default values get passed in with NULLs, fix them*/
SELECT
@what_to_check = LOWER(ISNULL(@what_to_check, 'all')),
@warnings_only = ISNULL(@warnings_only, 0),
@wait_duration_ms = ISNULL(@wait_duration_ms, 500),
@wait_round_interval_minutes = ISNULL(@wait_round_interval_minutes, 60),
@skip_locks = ISNULL(@skip_locks, 0),
@skip_waits = ISNULL(@skip_waits, 0),
@use_ring_buffer = ISNULL(@use_ring_buffer, 0),
@pending_task_threshold = ISNULL(@pending_task_threshold, 10);
/*Validate what to check*/
IF @what_to_check NOT IN
(
'all',
'cpu',
'disk',
'locking',
'memory',
'system',
'waits'
)
BEGIN
SELECT
@what_to_check =
CASE
WHEN @what_to_check = 'wait'
THEN 'waits'
WHEN @what_to_check IN
(
'blocking', 'blocks',
'deadlock', 'deadlocks',
'lock', 'locks'
)
THEN 'locking'
ELSE 'all'
END;
END;
/* 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'),
@log_retention_days =
CASE
WHEN @log_retention_days < 0
THEN ABS(@log_retention_days)
ELSE @log_retention_days
END;
/* 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;
SET
@log_database_schema =
QUOTENAME(@log_database_name) +
N'.' +
QUOTENAME(@log_schema_name) +
N'.';
/* Generate fully qualified table names */
SELECT
@log_table_significant_waits =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_SignificantWaits'),
@log_table_waits_by_count =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_WaitsByCount'),
@log_table_waits_by_duration =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_WaitsByDuration'),
@log_table_io_issues =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_IOIssues'),
@log_table_cpu_tasks =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_CPUTasks'),
@log_table_memory_conditions =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_MemoryConditions'),
@log_table_memory_broker =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_MemoryBroker'),
@log_table_memory_node_oom =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_MemoryNodeOOM'),
@log_table_system_health =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_SystemHealth'),
@log_table_scheduler_issues =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_SchedulerIssues'),
@log_table_severe_errors =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_SevereErrors'),
@log_table_pending_tasks =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_PendingTasks'),
@log_table_blocking =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_Blocking'),
@log_table_deadlocks =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_Deadlocks');
/* 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''_SignificantWaits''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_significant_waits + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
wait_type nvarchar(60) NULL,
duration_ms nvarchar(30) NULL,
signal_duration_ms nvarchar(30) NULL,
wait_resource nvarchar(256) NULL,
query_text xml NULL,
session_id integer NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for significant waits logging.'', 0, 1, ''' + @log_table_significant_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;
/* Create WaitsByCount table if it doesn't exist */
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''_WaitsByCount''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_waits_by_count + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time_rounded datetime2(7) NULL,
wait_type nvarchar(60) NULL,
waits nvarchar(30) NULL,
average_wait_time_ms nvarchar(30) NULL,
max_wait_time_ms nvarchar(30) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for waits by count logging.'', 0, 1, ''' + @log_table_waits_by_count + 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;
/* Create WaitsByDuration table if it doesn't exist */
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''_WaitsByDuration''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_waits_by_duration + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time_rounded datetime2(7) NULL,
wait_type nvarchar(60) NULL,
average_wait_time_ms nvarchar(30) NULL,
max_wait_time_ms nvarchar(30) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for waits by duration logging.'', 0, 1, ''' + @log_table_waits_by_duration + 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;
/* Create IOIssues table if it doesn't exist */
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''_IOIssues''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_io_issues + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
state nvarchar(256) NULL,
ioLatchTimeouts bigint NULL,
intervalLongIos bigint NULL,
totalLongIos bigint NULL,
longestPendingRequests_duration_ms nvarchar(30) NULL,
longestPendingRequests_filePath nvarchar(500) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for IO issues logging.'', 0, 1, ''' + @log_table_io_issues + 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;
/* Create CPUTasks table if it doesn't exist */
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''_CPUTasks''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_cpu_tasks + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
state nvarchar(256) NULL,
maxWorkers bigint NULL,
workersCreated bigint NULL,
workersIdle bigint NULL,
tasksCompletedWithinInterval bigint NULL,
pendingTasks bigint NULL,
oldestPendingTaskWaitingTime bigint NULL,
hasUnresolvableDeadlockOccurred bit NULL,
hasDeadlockedSchedulersOccurred bit NULL,
didBlockingOccur bit NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for CPU tasks logging.'', 0, 1, ''' + @log_table_cpu_tasks + 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;
/* Create MemoryConditions table if it doesn't exist */
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''_MemoryConditions''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory_conditions + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
lastNotification nvarchar(128) NULL,
outOfMemoryExceptions bigint NULL,
isAnyPoolOutOfMemory bit NULL,
processOutOfMemoryPeriod bigint NULL,
name nvarchar(128) NULL,
available_physical_memory_gb bigint NULL,
available_virtual_memory_gb bigint NULL,
available_paging_file_gb bigint NULL,
working_set_gb bigint NULL,
percent_of_committed_memory_in_ws bigint NULL,
page_faults bigint NULL,
system_physical_memory_high bigint NULL,
system_physical_memory_low bigint NULL,
process_physical_memory_low bigint NULL,
process_virtual_memory_low bigint NULL,
vm_reserved_gb bigint NULL,
vm_committed_gb bigint NULL,
locked_pages_allocated bigint NULL,
large_pages_allocated bigint NULL,
emergency_memory_gb bigint NULL,
emergency_memory_in_use_gb bigint NULL,
target_committed_gb bigint NULL,
current_committed_gb bigint NULL,
pages_allocated bigint NULL,
pages_reserved bigint NULL,
pages_free bigint NULL,
pages_in_use bigint NULL,
page_alloc_potential bigint NULL,
numa_growth_phase bigint NULL,
last_oom_factor bigint NULL,
last_os_error bigint NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory conditions logging.'', 0, 1, ''' + @log_table_memory_conditions + 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;
/* Create MemoryBroker table if it doesn't exist */
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''_MemoryBroker''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory_broker + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
broker_id bigint NULL,
pool_metadata_id bigint NULL,
delta_time bigint NULL,
memory_ratio bigint NULL,
new_target bigint NULL,
overall bigint NULL,
rate bigint NULL,
currently_predicated bigint NULL,
currently_allocated bigint NULL,
previously_allocated bigint NULL,
broker nvarchar(256) NULL,
notification nvarchar(256) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory broker logging.'', 0, 1, ''' + @log_table_memory_broker + 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;
/* Create MemoryNodeOOM table if it doesn't exist */
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''_MemoryNodeOOM''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_memory_node_oom + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
node_id bigint NULL,
memory_node_id bigint NULL,
memory_utilization_pct bigint NULL,
total_physical_memory_kb bigint NULL,
available_physical_memory_kb bigint NULL,
total_page_file_kb bigint NULL,
available_page_file_kb bigint NULL,
total_virtual_address_space_kb bigint NULL,
available_virtual_address_space_kb bigint NULL,
target_kb bigint NULL,
reserved_kb bigint NULL,
committed_kb bigint NULL,
shared_committed_kb numeric(38,0) NULL,
awe_kb bigint NULL,
pages_kb bigint NULL,
failure_type nvarchar(256) NULL,
failure_value bigint NULL,
resources bigint NULL,
factor_text nvarchar(256) NULL,
factor_value bigint NULL,
last_error bigint NULL,
pool_metadata_id bigint NULL,
is_process_in_job nvarchar(10) NULL,
is_system_physical_memory_high nvarchar(10) NULL,
is_system_physical_memory_low nvarchar(10) NULL,
is_process_physical_memory_low nvarchar(10) NULL,
is_process_virtual_memory_low nvarchar(10) NULL,
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for memory node OOM logging.'', 0, 1, ''' + @log_table_memory_node_oom + 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;
/* Create SystemHealth table if it doesn't exist */
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''_SystemHealth''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_system_health + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
event_time datetime2(7) NULL,
state nvarchar(256) NULL,
spinlockBackoffs bigint NULL,
sickSpinlockType nvarchar(256) NULL,
sickSpinlockTypeAfterAv nvarchar(256) NULL,
latchWarnings bigint NULL,
isAccessViolationOccurred bigint NULL,
writeAccessViolationCount bigint NULL,
totalDumpRequests bigint NULL,
intervalDumpRequests bigint NULL,
nonYieldingTasksReported bigint NULL,
pageFaults bigint NULL,
systemCpuUtilization bigint NULL,
sqlCpuUtilization bigint NULL,