-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_HumanEventsBlockViewer.sql
More file actions
4235 lines (3995 loc) · 135 KB
/
sp_HumanEventsBlockViewer.sql
File metadata and controls
4235 lines (3995 loc) · 135 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_HumanEventsBlockViewer
@help = 1;
For working through errors:
EXECUTE sp_HumanEventsBlockViewer
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID(N'dbo.sp_HumanEventsBlockViewer', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_HumanEventsBlockViewer AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_HumanEventsBlockViewer
(
@session_name sysname = N'keeper_HumanEvents_blocking', /*Event session name*/
@target_type sysname = NULL, /*ring buffer, file, or table*/
@start_date datetime2 = NULL, /*when to start looking for blocking*/
@end_date datetime2 = NULL, /*when to stop looking for blocking*/
@database_name sysname = NULL, /*target a specific database*/
@object_name sysname = NULL, /*target a specific schema-prefixed table*/
@target_database sysname = NULL, /*database containing the table with BPR data*/
@target_schema sysname = NULL, /*schema of the table*/
@target_table sysname = NULL, /*table name*/
@target_column sysname = NULL, /*column containing XML data*/
@timestamp_column sysname = NULL, /*column containing UTC timestamp (optional); see @help = 1 for details*/
@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 = 'HumanEventsBlockViewer', /*prefix for all logging tables*/
@log_retention_days integer = 30, /*Number of days to keep logs, 0 = keep indefinitely*/
@max_blocking_events integer = 5000, /*maximum blocking events to analyze, 0 = unlimited*/
@help bit = 0, /*get help with this procedure*/
@debug bit = 0, /*print dynamic sql and select temp table contents*/
@version varchar(30) = NULL OUTPUT, /*check the version number*/
@version_date datetime = NULL OUTPUT /*check the version date*/
)
WITH RECOMPILE
AS
BEGIN
SET STATISTICS XML OFF;
SET NOCOUNT ON;
SET XACT_ABORT OFF;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@version = '5.6',
@version_date = '20260501';
IF @help = 1
BEGIN
SELECT
introduction =
'hi, i''m sp_HumanEventsBlockViewer!' UNION ALL
SELECT 'you can use me in conjunction with sp_HumanEvents to quickly parse the sqlserver.blocked_process_report event' UNION ALL
SELECT 'EXECUTE sp_HumanEvents @event_type = N''blocking'', @keep_alive = 1;' UNION ALL
SELECT 'it will also work with any other extended event session that captures blocking' UNION ALL
SELECT 'just use the @session_name parameter to point me there' UNION ALL
SELECT 'EXECUTE dbo.sp_HumanEventsBlockViewer @session_name = N''blocked_process_report'';' UNION ALL
SELECT 'the system_health session also works, if you are okay with its lousy blocked process report'
SELECT 'all scripts and documentation are available here: https://code.erikdarling.com' UNION ALL
SELECT 'from your loving sql server consultant, erik darling: https://erikdarling.com';
SELECT
parameter_name =
ap.name,
data_type = t.name,
description =
CASE ap.name
WHEN N'@session_name' THEN 'name of the extended event session to pull from'
WHEN N'@target_type' THEN 'target type of the extended event session (ring buffer, file) or ''table'' to read from a table'
WHEN N'@start_date' THEN 'filter by date'
WHEN N'@end_date' THEN 'filter by date'
WHEN N'@database_name' THEN 'filter by database name'
WHEN N'@object_name' THEN 'filter by table name'
WHEN N'@target_database' THEN 'database containing the table with blocked process report data'
WHEN N'@target_schema' THEN 'schema of the table containing blocked process report data'
WHEN N'@target_table' THEN 'table containing blocked process report data'
WHEN N'@target_column' THEN 'column containing blocked process report XML'
WHEN N'@timestamp_column' THEN 'column containing UTC timestamp for filtering (optional). MUST be stored in UTC — @start_date and @end_date are shifted to UTC internally to match the XML @timestamp attribute, and the same UTC-shifted values are used for this column filter. A column in local time will be filtered against the wrong window.'
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'@max_blocking_events' THEN N'maximum blocking events to analyze, 0 = unlimited'
WHEN N'@help' THEN 'how you got here'
WHEN N'@debug' THEN 'dumps raw temp table contents'
WHEN N'@version' THEN 'OUTPUT; for support'
WHEN N'@version_date' THEN 'OUTPUT; for support'
END,
valid_inputs =
CASE ap.name
WHEN N'@session_name' THEN 'extended event session name capturing sqlserver.blocked_process_report, system_health also works'
WHEN N'@target_type' THEN 'event_file or ring_buffer or table'
WHEN N'@start_date' THEN 'a reasonable date'
WHEN N'@end_date' THEN 'a reasonable date'
WHEN N'@database_name' THEN 'a database that exists on this server'
WHEN N'@object_name' THEN 'a schema-prefixed table name'
WHEN N'@target_database' THEN 'a database that exists on this server'
WHEN N'@target_schema' THEN 'a schema in the target database'
WHEN N'@target_table' THEN 'a table in the target schema'
WHEN N'@target_column' THEN 'an XML column containing blocked process report data'
WHEN N'@timestamp_column' THEN 'a datetime / datetime2 / datetimeoffset column storing UTC timestamps'
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'@max_blocking_events' THEN N'0 to 2147483647 (0 = unlimited)'
WHEN N'@help' THEN '0 or 1'
WHEN N'@debug' THEN '0 or 1'
WHEN N'@version' THEN 'none; OUTPUT'
WHEN N'@version_date' THEN 'none; OUTPUT'
END,
defaults =
CASE ap.name
WHEN N'@session_name' THEN 'keeper_HumanEvents_blocking'
WHEN N'@target_type' THEN 'NULL'
WHEN N'@start_date' THEN 'NULL; will shortcut to last 7 days'
WHEN N'@end_date' THEN 'NULL'
WHEN N'@database_name' THEN 'NULL'
WHEN N'@object_name' THEN 'NULL'
WHEN N'@target_database' THEN 'NULL'
WHEN N'@target_schema' THEN 'NULL'
WHEN N'@target_table' THEN 'NULL'
WHEN N'@target_column' THEN 'NULL'
WHEN N'@timestamp_column' THEN 'NULL'
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'HumanEventsBlockViewer'
WHEN N'@log_retention_days' THEN N'30'
WHEN N'@max_blocking_events' THEN N'5000'
WHEN N'@help' THEN '0'
WHEN N'@debug' THEN '0'
WHEN N'@version' THEN 'none; OUTPUT'
WHEN N'@version_date' THEN 'none; OUTPUT'
END
FROM sys.all_parameters AS ap
JOIN sys.all_objects AS o
ON ap.object_id = o.object_id
JOIN sys.types AS t
ON ap.system_type_id = t.system_type_id
AND ap.user_type_id = t.user_type_id
WHERE o.name = N'sp_HumanEventsBlockViewer'
ORDER BY
ap.parameter_id
OPTION(RECOMPILE);
SELECT
blocked_process_report_setup =
N'check the messages tab for setup commands';
RAISERROR('
Unless you want to use the lousy version in system_health, the blocked process report needs to be enabled:
EXECUTE sys.sp_configure ''show advanced options'', 1;
EXECUTE sys.sp_configure ''blocked process threshold'', 5; /* Seconds of blocking before a report is generated */
RECONFIGURE;', 0, 1) WITH NOWAIT;
RAISERROR('
/*Create an extended event to log the blocked process report*/
/*
This won''t work in Azure SQLDB, you need to customize it to create:
* ON DATABASE instead of ON SERVER
* With a ring_buffer target
*/
CREATE EVENT SESSION
blocked_process_report
ON SERVER
ADD EVENT
sqlserver.blocked_process_report
ADD TARGET
package0.event_file
(
SET filename = N''bpr''
)
WITH
(
MAX_MEMORY = 4096KB,
EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY = 5 SECONDS,
MAX_EVENT_SIZE = 0KB,
MEMORY_PARTITION_MODE = NONE,
TRACK_CAUSALITY = OFF,
STARTUP_STATE = ON
);
ALTER EVENT SESSION
blocked_process_report
ON SERVER
STATE = START; ', 0, 1) WITH NOWAIT;
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;
/*Check if the blocked process report is on at all*/
IF EXISTS
(
SELECT
1/0
FROM sys.configurations AS c
WHERE c.name = N'blocked process threshold (s)'
AND CONVERT(integer, c.value_in_use) = 0
)
AND @session_name NOT LIKE N'system%health'
BEGIN
RAISERROR(N'Unless you want to use the lousy version in system_health, the blocked process report needs to be enabled:
EXECUTE sys.sp_configure ''show advanced options'', 1;
EXECUTE sys.sp_configure ''blocked process threshold'', 5; /* Seconds of blocking before a report is generated */
RECONFIGURE;',
11, 0) WITH NOWAIT;
RETURN;
END;
/*Check if the blocked process report is well-configured*/
IF EXISTS
(
SELECT
1/0
FROM sys.configurations AS c
WHERE c.name = N'blocked process threshold (s)'
AND CONVERT(integer, c.value_in_use) <> 5
)
AND @session_name NOT LIKE N'system%health'
BEGIN
RAISERROR(N'For best results, set up the blocked process report like this:
EXECUTE sys.sp_configure ''show advanced options'', 1;
EXECUTE sys.sp_configure ''blocked process threshold'', 5; /* Seconds of blocking before a report is generated */
RECONFIGURE;',
10, 0) WITH NOWAIT;
END;
/*Set some variables for better decision-making later*/
IF @debug = 1
BEGIN
RAISERROR('Declaring variables', 0, 1) WITH NOWAIT;
END;
DECLARE
@azure bit =
CASE
WHEN CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 5
THEN 1
ELSE 0
END,
@azure_msg nchar(1),
@session_id integer,
@target_session_id integer,
@file_name nvarchar(4000),
@is_system_health bit = 0,
@is_system_health_msg nchar(1),
@inputbuf_bom nvarchar(1) =
CONVERT(nvarchar(1), 0x0a00, 0),
@start_date_original datetime2 = @start_date,
@end_date_original datetime2 = @end_date,
@validation_sql nvarchar(max),
@extract_sql nvarchar(max),
/*Log to table stuff*/
@log_table_blocking 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 nvarchar(max) = N'',
@actual_start_date datetime2(7),
@actual_end_date datetime2(7),
@actual_event_count bigint;
/*Use some sane defaults for input parameters*/
IF @debug = 1
BEGIN
RAISERROR('Setting variables', 0, 1) WITH NOWAIT;
END;
SELECT
@start_date =
CASE
WHEN @start_date IS NULL
THEN
DATEADD
(
MINUTE,
DATEDIFF
(
MINUTE,
SYSDATETIME(),
GETUTCDATE()
),
DATEADD
(
DAY,
-7,
SYSDATETIME()
)
)
ELSE
DATEADD
(
MINUTE,
DATEDIFF
(
MINUTE,
SYSDATETIME(),
GETUTCDATE()
),
@start_date
)
END,
@end_date =
CASE
WHEN @end_date IS NULL
THEN
DATEADD
(
MINUTE,
DATEDIFF
(
MINUTE,
SYSDATETIME(),
GETUTCDATE()
),
SYSDATETIME()
)
ELSE
DATEADD
(
MINUTE,
DATEDIFF
(
MINUTE,
SYSDATETIME(),
GETUTCDATE()
),
@end_date
)
END,
@is_system_health =
CASE
WHEN @session_name LIKE N'system%health'
THEN 1
ELSE 0
END,
@mdsql = 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;';
IF @debug = 1
AND @is_system_health = 0
BEGIN
RAISERROR('We are not using system_health', 0, 1) WITH NOWAIT;
END;
IF @is_system_health = 1
BEGIN
RAISERROR('For best results, consider not using system_health as your target. Re-run with @help = 1 for guidance.', 0, 1) WITH NOWAIT;
END
/*
Note: I do not allow logging to a table from system_health, because the set of columns
and available data is too incomplete, and I don't want to juggle multiple
table definitions.
Logging to a table is only allowed from a blocked_process_report Extended Event,
but it can either be ring buffer or file target. I don't care about that.
*/
IF @is_system_health = 1
AND
(
LOWER(@target_type) = N'table'
OR @log_to_table = 1
)
BEGIN
RAISERROR('Logging system_health to a table is not supported.
Either pick a different session or change both
@target_type to be ''event_file'' or ''ring_buffer''
and @log_to_table to be 0.', 11, 0) WITH NOWAIT;
RETURN;
END
IF @is_system_health = 1
AND @target_type IS NULL
BEGIN
RAISERROR('No @target_type specified, using the ''event_file'' for system_health.', 0, 1) WITH NOWAIT;
SELECT
@target_type = 'event_file';
END
SELECT
@azure_msg =
CONVERT(nchar(1), @azure),
@is_system_health_msg =
CONVERT(nchar(1), @is_system_health);
/*Change this here in case someone leave it NULL*/
IF ISNULL(@target_database, DB_NAME()) IS NOT NULL
AND ISNULL(@target_schema, N'dbo') IS NOT NULL
AND @target_table IS NOT NULL
AND @target_column IS NOT NULL
AND @is_system_health = 0
BEGIN
SET @target_type = N'table';
END;
/* Check for table input early and validate */
IF LOWER(@target_type) = N'table'
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Table source detected, validating parameters', 0, 1) WITH NOWAIT;
END;
IF @target_database IS NULL
BEGIN
SET @target_database = DB_NAME();
END;
IF @target_schema IS NULL
BEGIN
SET @target_schema = N'dbo'
END;
/* Parameter validation */
IF @target_table IS NULL
OR @target_column IS NULL
BEGIN
RAISERROR(N'
When @target_type is ''table'', you must specify @target_table and @target_column.
When @target_database or @target_schema is NULL, they default to DB_NAME() and dbo.
',
11, 1) WITH NOWAIT;
RETURN;
END;
/* Check if target database exists */
IF NOT EXISTS
(
SELECT
1/0
FROM sys.databases AS d
WHERE d.name = @target_database
)
BEGIN
RAISERROR(N'The specified @target_database ''%s'' does not exist.', 11, 1, @target_database) WITH NOWAIT;
RETURN;
END;
/* Use dynamic SQL to validate schema, table, and column existence */
SET @validation_sql = N'
/*Validate schema exists*/
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
WHERE s.name = @schema
)
BEGIN
RAISERROR(N''The specified @target_schema %s does not exist in @database %s'', 11, 1, @schema, @database) WITH NOWAIT;
RETURN;
END;
/*Validate table exists*/
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.tables AS t
JOIN ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE t.name = @table
AND s.name = @schema
)
BEGIN
RAISERROR(N''The specified @target_table %s does not exist in @schema %s in database %s'', 11, 1, @table, @schema, @database) WITH NOWAIT;
RETURN;
END;
/*Validate column name exists*/
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.columns AS c
JOIN ' + QUOTENAME(@target_database) + N'.sys.tables AS t
ON c.object_id = t.object_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE c.name = @column
AND t.name = @table
AND s.name = @schema
)
BEGIN
RAISERROR(N''The specified @target_column %s does not exist in table %s.%s in database %s'', 11, 1, @column, @schema, @table, @database) WITH NOWAIT;
RETURN;
END;
/* Validate column is XML type */
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.columns AS c
JOIN ' + QUOTENAME(@target_database) + N'.sys.types AS ty
ON c.user_type_id = ty.user_type_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.tables AS t
ON c.object_id = t.object_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE c.name = @column
AND t.name = @table
AND s.name = @schema
AND ty.name = ''xml''
)
BEGIN
RAISERROR(N''The specified @target_column %s must be of XML data type.'', 11, 1, @column) WITH NOWAIT;
RETURN;
END;
';
/* Validate timestamp_column if specified */
IF @timestamp_column IS NOT NULL
BEGIN
SET @validation_sql = @validation_sql + N'
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.columns AS c
JOIN ' + QUOTENAME(@target_database) + N'.sys.tables AS t
ON c.object_id = t.object_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE c.name = @timestamp_column
AND t.name = @table
AND s.name = @schema
)
BEGIN
RAISERROR(N''The specified @timestamp_column %s does not exist in table %s.%s in database %s'', 11, 1, @timestamp_column, @schema, @table, @database) WITH NOWAIT;
RETURN;
END;
/* Validate timestamp column is date-ish type */
IF NOT EXISTS
(
SELECT
1/0
FROM ' + QUOTENAME(@target_database) + N'.sys.columns AS c
JOIN ' + QUOTENAME(@target_database) + N'.sys.types AS ty
ON c.user_type_id = ty.user_type_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.tables AS t
ON c.object_id = t.object_id
JOIN ' + QUOTENAME(@target_database) + N'.sys.schemas AS s
ON t.schema_id = s.schema_id
WHERE c.name = @timestamp_column
AND t.name = @table
AND s.name = @schema
AND ty.name LIKE N''%date%''
)
BEGIN
RAISERROR(N''The specified @timestamp_column %s must be of datetime data type.'', 11, 1, @timestamp_column) WITH NOWAIT;
RETURN;
END;';
END;
IF @debug = 1
BEGIN
PRINT @validation_sql;
END;
EXECUTE sys.sp_executesql
@validation_sql,
N'
@database sysname,
@schema sysname,
@table sysname,
@column sysname,
@timestamp_column sysname
',
@target_database,
@target_schema,
@target_table,
@target_column,
@timestamp_column;
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_blocking =
@log_database_schema +
QUOTENAME(@log_table_name_prefix + N'_BlockedProcessReport');
/* 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''_BlockedProcessReport''
AND s.name = @schema_name
)
BEGIN
CREATE TABLE ' + @log_table_blocking + N'
(
id bigint IDENTITY,
collection_time datetime2(7) NOT NULL DEFAULT SYSDATETIME(),
blocked_process_report varchar(22) NOT NULL,
event_time datetime2(7) NULL,
database_name sysname NULL,
currentdbname sysname NULL,
contentious_object nvarchar(4000) NULL,
activity varchar(8) NULL,
blocking_tree varchar(8000) NULL,
spid integer NULL,
ecid integer NULL,
query_text xml NULL,
wait_time_ms bigint NULL,
status nvarchar(10) NULL,
isolation_level nvarchar(50) NULL,
lock_mode nvarchar(10) NULL,
resource_owner_type nvarchar(256) NULL,
transaction_count integer NULL,
transaction_name nvarchar(1024) NULL,
last_transaction_started datetime2(7) NULL,
last_transaction_completed datetime2(7) NULL,
client_option_1 varchar(261) NULL,
client_option_2 varchar(307) NULL,
wait_resource nvarchar(1024) NULL,
priority integer NULL,
log_used bigint NULL,
client_app nvarchar(256) NULL,
host_name nvarchar(256) NULL,
login_name nvarchar(256) NULL,
transaction_id bigint NULL,
blocked_process_report_xml xml NULL
PRIMARY KEY CLUSTERED (collection_time, id)
);
IF @debug = 1 BEGIN RAISERROR(''Created table %s for significant waits logging.'', 0, 1, ''' + @log_table_blocking + 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 @dsql = N'
DELETE FROM ' + @log_table_blocking + '
WHERE collection_time < @cleanup_date;';
IF @debug = 1 BEGIN PRINT @dsql; END;
EXECUTE sys.sp_executesql
@dsql,
N'@cleanup_date datetime2(7)',
@cleanup_date;
IF @debug = 1
BEGIN
RAISERROR('Log cleanup complete', 0, 1) WITH NOWAIT;
END;
END;
END;
/*Temp tables for staging results*/
IF @debug = 1
BEGIN
RAISERROR('Creating temp tables', 0, 1) WITH NOWAIT;
END;
CREATE TABLE
#x
(
x xml
);
CREATE TABLE
#blocking_xml
(
human_events_xml xml
);
CREATE TABLE
#block_findings
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
check_id integer NOT NULL,
database_name sysname NULL,
object_name nvarchar(1000) NULL,
finding_group nvarchar(100) NULL,
finding nvarchar(4000) NULL,
sort_order bigint
);
CREATE TABLE
#sp_server_diagnostics_component_result
(
sp_server_diagnostics_component_result xml
);
IF LOWER(@target_type) = N'table'
BEGIN
GOTO TableMode;
END;
/*Look to see if the session exists and is running*/
IF @debug = 1
BEGIN
RAISERROR('Checking if the session exists', 0, 1) WITH NOWAIT;
END;
IF @azure = 0
BEGIN
IF NOT EXISTS
(
SELECT
1/0
FROM sys.server_event_sessions AS ses
JOIN sys.dm_xe_sessions AS dxs
ON dxs.name = ses.name
WHERE ses.name = @session_name
AND dxs.create_time IS NOT NULL
)
BEGIN
RAISERROR('A session with the name %s does not exist or is not currently active.', 11, 1, @session_name) WITH NOWAIT;
RETURN;
END;
END;
IF @azure = 1
BEGIN
IF NOT EXISTS
(
SELECT
1/0
FROM sys.database_event_sessions AS ses
JOIN sys.dm_xe_database_sessions AS dxs
ON dxs.name = ses.name
WHERE ses.name = @session_name
AND dxs.create_time IS NOT NULL
)
BEGIN
RAISERROR('A session with the name %s does not exist or is not currently active.', 11, 1, @session_name) WITH NOWAIT;
RETURN;
END;
END;
/*Figure out if we have a file or ring buffer target*/
IF @debug = 1
BEGIN
RAISERROR('What kind of target does %s have?', 0, 1, @session_name) WITH NOWAIT;
END;
/*
Auto-detect @target_type when not supplied. When a session has both
targets attached, ORDER BY t.target_name picks 'event_file' over
'ring_buffer' alphabetically — this is DELIBERATE. event_file is the
more reliable target (ring_buffer has a finite in-memory window and
drops older events under pressure), so a blocking report built from
the file target has a better chance of covering the full window the
caller asked for. Don't "fix" the ORDER BY to ring_buffer unless you
want faster but less complete reads.
*/
IF @target_type IS NULL
AND @is_system_health = 0
BEGIN
IF @azure = 0
BEGIN
SELECT TOP (1)
@target_type =
t.target_name
FROM sys.dm_xe_sessions AS s
JOIN sys.dm_xe_session_targets AS t
ON s.address = t.event_session_address
WHERE s.name = @session_name
ORDER BY
t.target_name
OPTION(RECOMPILE);
END;
IF @azure = 1
BEGIN
SELECT TOP (1)
@target_type =
t.target_name
FROM sys.dm_xe_database_sessions AS s
JOIN sys.dm_xe_database_session_targets AS t
ON s.address = t.event_session_address
WHERE s.name = @session_name
ORDER BY
t.target_name
OPTION(RECOMPILE);
END;
END;
/*
Dump whatever we got into a temp table
Note that system_health hits this branch if we use the ring_buffer target.
*/
IF LOWER(@target_type) = N'ring_buffer'
BEGIN
IF @azure = 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR('Azure: %s', 0, 1, @azure_msg) WITH NOWAIT;
RAISERROR('Inserting to #x for target type: %s and system health: %s', 0, 1, @target_type, @is_system_health_msg) WITH NOWAIT;
END;
INSERT
#x WITH(TABLOCKX)
(
x
)