-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_HumanEvents.sql
More file actions
4790 lines (4475 loc) · 276 KB
/
sp_HumanEvents.sql
File metadata and controls
4790 lines (4475 loc) · 276 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 2025 Darling Data, LLC
https://www.erikdarling.com/
For usage and licensing details, run:
EXECUTE sp_HumanEvents
@help = 1;
For working through errors:
EXECUTE sp_HumanEvents
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
IF OBJECT_ID(N'dbo.sp_HumanEvents', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_HumanEvents AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_HumanEvents
(
@event_type sysname = N'query',
@query_duration_ms integer = 500,
@query_sort_order nvarchar(10) = N'cpu',
@skip_plans bit = 0,
@blocking_duration_ms integer = 500,
@wait_type nvarchar(4000) = N'ALL',
@wait_duration_ms integer = 10,
@client_app_name sysname = N'',
@client_hostname sysname = N'',
@database_name sysname = N'',
@session_id nvarchar(7) = N'',
@sample_divisor integer = 5,
@username sysname = N'',
@object_name sysname = N'',
@object_schema sysname = N'dbo',
@requested_memory_mb integer = 0,
@seconds_sample tinyint = 10,
@gimme_danger bit = 0,
@keep_alive bit = 0,
@custom_name sysname = N'',
@output_database_name sysname = N'',
@output_schema_name sysname = N'dbo',
@delete_retention_days integer = 3,
@cleanup bit = 0,
@max_memory_kb bigint = 102400,
@version varchar(30) = NULL OUTPUT,
@version_date datetime = NULL OUTPUT,
@debug bit = 0,
@help bit = 0
)
AS
BEGIN
SET STATISTICS XML OFF;
SET NOCOUNT ON;
SET XACT_ABORT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT
@version = '6.4',
@version_date = '20250401';
IF @help = 1
BEGIN
/*Warnings, I guess*/
SELECT [WARNING WARNING WARNING] =
N'warning! achtung! peligro! chardonnay!' UNION ALL
SELECT N'misuse of this procedure can harm performance' UNION ALL
SELECT N'be very careful about introducing observer overhead, especially when gathering query plans' UNION ALL
SELECT N'be even more careful when setting up permanent sessions!' UNION ALL
SELECT N'for additional support: https://code.erikdarling.com' UNION ALL
SELECT N'from your loving sql server consultant, erik darling: https://erikdarling.com';
/*Introduction*/
SELECT
introduction = N'allow me to reintroduce myself' UNION ALL
SELECT N'this can be used to start a time-limited extended event session to capture various things:' UNION ALL
SELECT N' * blocking' UNION ALL
SELECT N' * query performance and plans' UNION ALL
SELECT N' * compilations' UNION ALL
SELECT N' * recompilations' UNION ALL
SELECT N' * wait stats';
/*Limitations*/
SELECT
limitations = N'frigid shortcomings' UNION ALL
SELECT N'you need to be on at least SQL Server 2012 SP4 or higher to run this' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'if your version isn''t patched to where query_hash_signed is an available xe action, this won''t run' UNION ALL
SELECT N'sp_HumanEvents is designed to make getting information from common extended events easier. with that in mind,' UNION ALL
SELECT N'some of the customization is limited, and right now you can''t just choose your own adventure.' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'because i don''t want to create files, i''m using the ring buffer, which also has some pesky limitations.' UNION ALL
SELECT N'https://techcommunity.microsoft.com/t5/sql-server-support/you-may-not-see-the-data-you-expect-in-extended-event-ring/ba-p/315838' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'in order to use the "blocking" session, you must enable the blocked process report' UNION ALL
SELECT N'https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/blocked-process-threshold-server-configuration-option';
/*Usage*/
SELECT
parameter =
ap.name,
t.name,
description =
CASE ap.name
WHEN N'@event_type' THEN N'used to pick which session you want to run'
WHEN N'@query_duration_ms' THEN N'(>=) used to set a minimum query duration to collect data for'
WHEN N'@query_sort_order' THEN 'when you use the "query" event, lets you choose which metrics to sort results by'
WHEN N'@skip_plans' THEN 'when you use the "query" event, lets you skip collecting actual execution plans'
WHEN N'@blocking_duration_ms' THEN N'(>=) used to set a minimum blocking duration to collect data for'
WHEN N'@wait_type' THEN N'(inclusive) filter to only specific wait types'
WHEN N'@wait_duration_ms' THEN N'(>=) used to set a minimum time per wait to collect data for'
WHEN N'@client_app_name' THEN N'(inclusive) filter to only specific app names'
WHEN N'@client_hostname' THEN N'(inclusive) filter to only specific host names'
WHEN N'@database_name' THEN N'(inclusive) filter to only specific databases'
WHEN N'@session_id' THEN N'(inclusive) filter to only a specific session id, or a sample of session ids'
WHEN N'@sample_divisor' THEN N'the divisor for session ids when sampling a workload, e.g. SPID % 5'
WHEN N'@username' THEN N'(inclusive) filter to only a specific user'
WHEN N'@object_name' THEN N'(inclusive) to only filter to a specific object name'
WHEN N'@object_schema' THEN N'(inclusive) the schema of the object you want to filter to; only needed with blocking events'
WHEN N'@requested_memory_mb' THEN N'(>=) the memory grant a query must ask for to have data collected'
WHEN N'@seconds_sample' THEN N'the duration in seconds to run the event session for'
WHEN N'@gimme_danger' THEN N'used to override default minimums for query, wait, and blocking durations. only use if you''re okay with potentially adding a lot of observer overhead on your system, or for testing purposes.'
WHEN N'@debug' THEN N'use to print out dynamic SQL'
WHEN N'@keep_alive' THEN N'creates a permanent session, either to watch live or log to a table from'
WHEN N'@custom_name' THEN N'if you want to custom name a permanent session'
WHEN N'@output_database_name' THEN N'the database you want to log data to'
WHEN N'@output_schema_name' THEN N'the schema you want to log data to'
WHEN N'@delete_retention_days' THEN N'how many days of logged data you want to keep'
WHEN N'@cleanup' THEN N'deletes all sessions, tables, and views. requires output database and schema.'
WHEN N'@max_memory_kb' THEN N'set a max ring buffer size to log data to'
WHEN N'@help' THEN N'well you''re here so you figured this one out'
WHEN N'@version' THEN N'to make sure you have the most recent bits'
WHEN N'@version_date' THEN N'to make sure you have the most recent bits'
ELSE N'????'
END,
valid_inputs =
CASE ap.name
WHEN N'@event_type' THEN N'"blocking", "query", "waits", "recompiles", "compiles" and certain variations on those words'
WHEN N'@query_duration_ms' THEN N'an integer'
WHEN N'@query_sort_order' THEN '"cpu", "reads", "writes", "duration", "memory", "spills", and you can add "avg" to sort by averages, e.g. "avg cpu"'
WHEN N'@skip_plans' THEN '1 or 0'
WHEN N'@blocking_duration_ms' THEN N'an integer'
WHEN N'@wait_type' THEN N'a single wait type, or a CSV list of wait types'
WHEN N'@wait_duration_ms' THEN N'an integer'
WHEN N'@client_app_name' THEN N'a stringy thing'
WHEN N'@client_hostname' THEN N'a stringy thing'
WHEN N'@database_name' THEN N'a stringy thing'
WHEN N'@session_id' THEN N'an integer, or "sample" to sample a workload'
WHEN N'@sample_divisor' THEN N'an integer'
WHEN N'@username' THEN N'a stringy thing'
WHEN N'@object_name' THEN N'a stringy thing'
WHEN N'@object_schema' THEN N'a stringy thing'
WHEN N'@requested_memory_mb' THEN N'an integer'
WHEN N'@seconds_sample' THEN N'a tiny integer'
WHEN N'@gimme_danger' THEN N'1 or 0'
WHEN N'@debug' THEN N'1 or 0'
WHEN N'@keep_alive' THEN N'1 or 0'
WHEN N'@custom_name' THEN N'a stringy thing'
WHEN N'@output_database_name' THEN N'a valid database name'
WHEN N'@output_schema_name' THEN N'a valid schema'
WHEN N'@delete_retention_days' THEN N'a POSITIVE integer'
WHEN N'@cleanup' THEN N'1 or 0'
WHEN N'@max_memory_kb' THEN N'an integer'
WHEN N'@help' THEN N'1 or 0'
WHEN N'@version' THEN N'none, output'
WHEN N'@version_date' THEN N'none, output'
ELSE N'????'
END,
defaults =
CASE ap.name
WHEN N'@event_type' THEN N'"query"'
WHEN N'@query_duration_ms' THEN N'500 (ms)'
WHEN N'@query_sort_order' THEN N'"cpu"'
WHEN N'@skip_plans' THEN '0'
WHEN N'@blocking_duration_ms' THEN N'500 (ms)'
WHEN N'@wait_type' THEN N'"all", which uses a list of "interesting" waits'
WHEN N'@wait_duration_ms' THEN N'10 (ms)'
WHEN N'@client_app_name' THEN N'intentionally left blank'
WHEN N'@client_hostname' THEN N'intentionally left blank'
WHEN N'@database_name' THEN N'intentionally left blank'
WHEN N'@session_id' THEN N'intentionally left blank'
WHEN N'@sample_divisor' THEN N'5'
WHEN N'@username' THEN N'intentionally left blank'
WHEN N'@object_name' THEN N'intentionally left blank'
WHEN N'@object_schema' THEN N'dbo'
WHEN N'@requested_memory_mb' THEN N'0'
WHEN N'@seconds_sample' THEN N'10'
WHEN N'@gimme_danger' THEN N'0'
WHEN N'@keep_alive' THEN N'0'
WHEN N'@custom_name' THEN N'intentionally left blank'
WHEN N'@output_database_name' THEN N'intentionally left blank'
WHEN N'@output_schema_name' THEN N'dbo'
WHEN N'@delete_retention_days' THEN N'3 (days)'
WHEN N'@debug' THEN N'0'
WHEN N'@cleanup' THEN N'0'
WHEN N'@max_memory_kb' THEN N'102400'
WHEN N'@help' THEN N'0'
WHEN N'@version' THEN N'none, output'
WHEN N'@version_date' THEN N'none, output'
ELSE N'????'
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_HumanEvents';
/*Example calls*/
SELECT
example_calls = N'EXAMPLE CALLS' UNION ALL
SELECT N'note that not all filters are compatible with all sessions' UNION ALL
SELECT N'this is handled dynamically, but please don''t think you''re crazy if one "doesn''t work"' UNION ALL
SELECT N'to capture all types of "completed" queries that have run for at least one second for 20 seconds from a specific database' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''query'', @query_duration_ms = 1000, @seconds_sample = 20, @database_name = ''YourMom'';' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'or that have asked for 1gb of memory' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''query'', @query_duration_ms = 1000, @seconds_sample = 20, @requested_memory_mb = 1024;' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'maybe you want to find unparameterized queries from a poorly written app' UNION ALL
SELECT N'newer versions will use sql_statement_post_compile, older versions will use uncached_sql_batch_statistics and sql_statement_recompile' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''compilations'', @client_app_name = N''GL00SNIFЯ'', @session_id = ''sample'', @sample_divisor = 3;' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'perhaps you think queries recompiling are the cause of your problems!' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''recompilations'', @seconds_sample = 30;' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'look, blocking is annoying. just turn on RCSI, you goblin.' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''blocking'', @seconds_sample = 60, @blocking_duration_ms = 5000;' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'i mean wait stats are probably a meme but whatever' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''waits'', @wait_duration_ms = 10, @seconds_sample = 100, @wait_type = N''all'';' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'note that THREADPOOL is SOS_WORKER in xe-land. why? i dunno.' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE dbo.sp_HumanEvents @event_type = ''waits'', @wait_duration_ms = 10, @seconds_sample = 100, @wait_type = N''SOS_WORKER,RESOURCE_SEMAPHORE,YOUR_MOM'';' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'to set up a permanent session for compiles, but you can specify any of the session types here' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE sp_HumanEvents @event_type = N''compiles'', @debug = 1, @keep_alive = 1;' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'to log to a database named whatever, and a schema called dbo' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'EXECUTE sp_HumanEvents @debug = 1, @output_database_name = N''whatever'', @output_schema_name = N''dbo'';' UNION ALL
SELECT REPLICATE(N'-', 100);
/*Views*/
SELECT
views_and_stuff = N'views that get created when you log to tables' UNION ALL
SELECT N'these will get created in the same database that your output tables get created in for simplicity' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_Queries: View to look at data pulled from logged queries' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_WaitsByQueryAndDatabase: waits generated grouped by query and database. this is best effort, as the query grouping relies on them being present in the plan cache' UNION ALL
SELECT N'HumanEvents_WaitsByDatabase: waits generated grouped by database' UNION ALL
SELECT N'HumanEvents_WaitsTotal: total waits' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_Blocking: view to assemble blocking chains' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_CompilesByDatabaseAndObject: compiles by database and object' UNION ALL
SELECT N'HumanEvents_CompilesByQuery: compiles by query' UNION ALL
SELECT N'HumanEvents_CompilesByDuration: compiles by duration length' UNION ALL
SELECT N'HumanEvents_Compiles_Legacy: compiles on older versions that don''t support new events' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_Parameterization: data collected from the parameterization event' UNION ALL
SELECT REPLICATE(N'-', 100) UNION ALL
SELECT N'HumanEvents_RecompilesByDatabaseAndObject: recompiles by database and object' UNION ALL
SELECT N'HumanEvents_RecompilesByQuery: recompiles by query' UNION ALL
SELECT N'HumanEvents_RecompilesByDuration: recompiles by long duration' UNION ALL
SELECT N'HumanEvents_Recompiles_Legacy: recompiles on older versions that don''t support new events' UNION ALL
SELECT REPLICATE(N'-', 100);
/*License to F5*/
SELECT
mit_license_yo = N'i am MIT licensed, so like, do whatever' UNION ALL
SELECT N'see printed messages for full license';
RAISERROR(N'
MIT License
Copyright 2025 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;
BEGIN TRY
CREATE TABLE
#x
(
x xml
);
CREATE TABLE
#drop_commands
(
id integer IDENTITY PRIMARY KEY,
drop_command nvarchar(1000)
);
CREATE TABLE
#user_waits
(
wait_type nvarchar(60)
);
CREATE TABLE
#papers_please
(
ahem sysname
);
CREATE TABLE
#human_events_xml_internal
(
human_events_xml xml
);
CREATE TABLE
#wait
(
wait_type sysname
);
CREATE TABLE
#human_events_worker
(
id integer NOT NULL PRIMARY KEY IDENTITY,
event_type sysname NOT NULL,
event_type_short sysname NOT NULL,
is_table_created bit NOT NULL DEFAULT 0,
is_view_created bit NOT NULL DEFAULT 0,
last_checked datetime NOT NULL DEFAULT '19000101',
last_updated datetime NOT NULL DEFAULT '19000101',
output_database sysname NOT NULL,
output_schema sysname NOT NULL,
output_table nvarchar(400) NOT NULL
);
CREATE UNIQUE NONCLUSTERED INDEX
no_dupes
ON #human_events_worker
(output_table)
WITH
(IGNORE_DUP_KEY = ON);
CREATE TABLE
#view_check
(
id integer PRIMARY KEY IDENTITY,
view_name sysname NOT NULL,
view_definition varbinary(max) NOT NULL,
output_database sysname NOT NULL DEFAULT N'',
output_schema sysname NOT NULL DEFAULT N'',
output_table sysname NOT NULL DEFAULT N'',
view_converted AS
CONVERT
(
nvarchar(max),
view_definition
),
view_converted_length AS
DATALENGTH
(
CONVERT
(
nvarchar(max),
view_definition
)
)
);
/*
I mean really stop it with the unsupported versions
*/
DECLARE
@v decimal(5,0) =
PARSENAME
(
CONVERT
(
nvarchar(128),
SERVERPROPERTY('ProductVersion')
),
4
),
@mv integer =
PARSENAME
(
CONVERT
(
nvarchar(128),
SERVERPROPERTY('ProductVersion')
),
2
),
@azure bit =
CASE
WHEN CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
) = 5
THEN 1
ELSE 0
END,
@drop_old_sql nvarchar(1000) = N'',
@waitfor nvarchar(20) = N'',
@session_name nvarchar(512) = N'',
@session_with nvarchar(max) = N'',
@session_sql nvarchar(max) = N'',
@start_sql nvarchar(max) = N'',
@stop_sql nvarchar(max) = N'',
@drop_sql nvarchar(max) = N'',
@session_filter nvarchar(max) = N'',
@session_filter_limited nvarchar(max) = N'',
@session_filter_query_plans nvarchar(max) = N'',
@session_filter_waits nvarchar(max) = N'',
@session_filter_recompile nvarchar(max)= N'',
@session_filter_statement_completed nvarchar(max) = N'',
@session_filter_blocking nvarchar(max) = N'',
@session_filter_parameterization nvarchar(max) = N'',
@query_duration_filter nvarchar(max) = N'',
@blocking_duration_ms_filter nvarchar(max) = N'',
@wait_type_filter nvarchar(max) = N'',
@wait_duration_filter nvarchar(max) = N'',
@client_app_name_filter nvarchar(max) = N'',
@client_hostname_filter nvarchar(max) = N'',
@database_name_filter nvarchar(max) = N'',
@session_id_filter nvarchar(max) = N'',
@username_filter nvarchar(max) = N'',
@object_name_filter nvarchar(max) = N'',
@requested_memory_mb_filter nvarchar(max) = N'',
@compile_events bit = 0,
@parameterization_events bit = 0,
@fully_formed_babby nvarchar(1000) = N'',
@s_out integer,
@s_sql nvarchar(max) = N'',
@s_params nvarchar(max) = N'',
@object_id sysname = N'',
@requested_memory_kb nvarchar(11) = N'',
@the_sleeper_must_awaken nvarchar(max) = N'',
@min_id integer,
@max_id integer,
@event_type_check sysname,
@object_name_check nvarchar(1000) = N'',
@table_sql nvarchar(max) = N'',
@view_tracker bit,
@spe nvarchar(max) = N'.sys.sp_executesql ',
@view_sql nvarchar(max) = N'',
@view_database sysname = N'',
@date_filter datetime,
@Time time,
@delete_tracker integer,
@the_deleter_must_awaken nvarchar(max) = N'',
@executer nvarchar(max),
@cleanup_sessions nvarchar(max) = N'',
@cleanup_tables nvarchar(max) = N'',
@drop_holder nvarchar(max) = N'',
@cleanup_views nvarchar(max) = N'',
@nc10 nvarchar(2) = NCHAR(10),
@inputbuf_bom nvarchar(1) = CONVERT(nvarchar(1), 0x0a00, 0);
/*check to make sure we're on a usable version*/
IF
(
@v < 11
OR
(
@v = 11
AND @mv < 7001
)
)
BEGIN
RAISERROR(N'This darn thing doesn''t seem to work on versions older than 2012 SP4.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*one more check here for old versions. loiterers should arrested.*/
IF NOT EXISTS
(
SELECT
1/0
FROM sys.dm_xe_packages AS xp
JOIN sys.dm_xe_objects AS xo
ON xp.guid = xo.package_guid
WHERE (xo.capabilities IS NULL
OR xo.capabilities & 1 = 0)
AND (xp.capabilities IS NULL
OR xp.capabilities & 1 = 0)
AND xo.object_type = N'action'
AND xo.name = N'query_hash_signed'
)
BEGIN
RAISERROR(N'This server hasn''t been patched up to a supported version that has the query_hash_signed action.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*clean up any old/dormant sessions*/
IF @azure = 0
BEGIN
INSERT
#drop_commands WITH(TABLOCK)
(
drop_command
)
SELECT
N'DROP EVENT SESSION ' +
ses.name +
N' ON SERVER;'
FROM sys.server_event_sessions AS ses
LEFT JOIN sys.dm_xe_sessions AS dxe
ON dxe.name = ses.name
WHERE ses.name LIKE N'HumanEvents%'
AND (dxe.create_time < DATEADD(MINUTE, -1, SYSDATETIME())
OR dxe.create_time IS NULL);
END;
IF @azure = 1
BEGIN
INSERT
#drop_commands WITH(TABLOCK)
(
drop_command
)
SELECT
N'DROP EVENT SESSION ' +
ses.name +
N' ON DATABASE;'
FROM sys.database_event_sessions AS ses
LEFT JOIN sys.dm_xe_database_sessions AS dxe
ON dxe.name = ses.name
WHERE ses.name LIKE N'HumanEvents%'
AND (dxe.create_time < DATEADD(MINUTE, -1, SYSDATETIME())
OR dxe.create_time IS NULL);
END;
IF EXISTS
(
SELECT
1/0
FROM #drop_commands AS dc
)
BEGIN
RAISERROR(N'Found old sessions, dropping those.', 0, 1) WITH NOWAIT;
DECLARE
@drop_cursor CURSOR;
SET
@drop_cursor =
CURSOR
LOCAL
SCROLL
DYNAMIC
READ_ONLY
FOR
SELECT
drop_command
FROM #drop_commands;
OPEN @drop_cursor;
FETCH NEXT
FROM @drop_cursor
INTO @drop_old_sql;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @drop_old_sql;
EXECUTE (@drop_old_sql);
FETCH NEXT
FROM @drop_cursor
INTO @drop_old_sql;
END;
END;
IF @debug = 1 BEGIN RAISERROR(N'Setting up some variables', 0, 1) WITH NOWAIT; END;
/* Give sessions super unique names in case more than one person uses it at a time */
IF @keep_alive = 0
BEGIN
SET @session_name +=
REPLACE
(
N'HumanEvents_' +
@event_type +
N'_' +
CONVERT
(
nvarchar(36),
NEWID()
),
N'-',
N''
);
END;
IF @keep_alive = 1
BEGIN
SET @session_name +=
N'keeper_HumanEvents_' +
@event_type +
CASE
WHEN @custom_name <> N''
THEN N'_' + @custom_name
ELSE N''
END;
END;
/* set a lower max memory setting for azure */
IF @azure = 1
BEGIN
SELECT TOP (1)
@max_memory_kb =
CONVERT
(
bigint,
(rg.max_memory * .10) * 1024
)
FROM sys.dm_user_db_resource_governance AS rg
WHERE UPPER(rg.database_name) = UPPER(QUOTENAME(@database_name))
OR @database_name = ''
ORDER BY
max_memory DESC;
IF @debug = 1 BEGIN RAISERROR(N'Setting lower max memory for ringbuffer due to Azure, setting to %m kb', 0, 1, @max_memory_kb) WITH NOWAIT; END;
END;
/* session create options */
SET @session_with = N'
ADD TARGET package0.ring_buffer
( SET max_memory = ' + RTRIM(@max_memory_kb) + N' )
WITH
(
MAX_MEMORY = ' + RTRIM(@max_memory_kb) + N'KB,
EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY = 5 SECONDS,
MAX_EVENT_SIZE = 0KB,
MEMORY_PARTITION_MODE = PER_CPU,
TRACK_CAUSALITY = OFF,
STARTUP_STATE = OFF
);' + @nc10;
/* azure can't create on server, just database */
SET @session_sql =
N'
CREATE EVENT SESSION ' +
@session_name +
CASE
WHEN @azure = 0
THEN N'
ON SERVER '
ELSE N'
ON DATABASE '
END;
/* STOP. DROP. SHUT'EM DOWN OPEN UP SHOP. */
SET @start_sql =
N'ALTER EVENT SESSION ' +
@session_name +
N' ON ' +
CASE
WHEN @azure = 1
THEN 'DATABASE'
ELSE 'SERVER'
END +
' STATE = START;' +
@nc10;
SET @stop_sql =
N'ALTER EVENT SESSION ' +
@session_name +
N' ON ' +
CASE
WHEN @azure = 1
THEN N'DATABASE'
ELSE N'SERVER'
END +
N' STATE = STOP;' +
@nc10;
SET @drop_sql =
N'DROP EVENT SESSION ' +
@session_name +
N' ON ' +
CASE
WHEN @azure = 1
THEN N'DATABASE'
ELSE N'SERVER'
END +
N';' +
@nc10;
/*Some sessions can use all general filters*/
SET @session_filter = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*Others can't use all of them, like app and host name*/
SET @session_filter_limited = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*query plans can filter on requested memory, too, along with the limited filters*/
SET @session_filter_query_plans = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*only wait stats can filter on wait types, but can filter on everything else*/
SET @session_filter_waits = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*only wait stats can filter on wait types, but can filter on everything else*/
SET @session_filter_recompile = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*sql_statement_completed can do everything except object name*/
SET @session_filter_statement_completed = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
/*for blocking because blah blah*/
SET @session_filter_blocking = @nc10 + N' sqlserver.is_system = 1 ' + @nc10;
/*for parameterization because blah blah*/
SET @session_filter_parameterization = @nc10 + N' sqlserver.is_system = 0 ' + @nc10;
IF @debug = 1 BEGIN RAISERROR(N'Checking for some event existence', 0, 1) WITH NOWAIT; END;
/* Determines if we use the new event or the old event(s) to track compiles */
IF EXISTS
(
SELECT
1/0
FROM sys.dm_xe_objects AS dxo
WHERE dxo.name = N'sql_statement_post_compile'
)
BEGIN
SET @compile_events = 1;
END;
/* Or if we use this event at all! */
IF EXISTS
(
SELECT
1/0
FROM sys.dm_xe_objects AS dxo
WHERE dxo.name = N'query_parameterization_data'
)
BEGIN
SET @parameterization_events = 1;
END;
/* You know what I don't wanna deal with? NULLs. */
IF @debug = 1 BEGIN RAISERROR(N'Nixing NULLs', 0, 1) WITH NOWAIT; END;
SET @event_type = ISNULL(@event_type, N'');
SET @client_app_name = ISNULL(@client_app_name, N'');
SET @client_hostname = ISNULL(@client_hostname, N'');
SET @database_name = ISNULL(@database_name, N'');
SET @session_id = ISNULL(@session_id, N'');
SET @username = ISNULL(@username, N'');
SET @object_name = ISNULL(@object_name, N'');
SET @object_schema = ISNULL(@object_schema, N'');
SET @custom_name = ISNULL(@custom_name, N'');
SET @output_database_name = ISNULL(@output_database_name, N'');
SET @output_schema_name = ISNULL(@output_schema_name, N'');
/*I'm also very forgiving of some white space*/
SET @database_name = RTRIM(LTRIM(@database_name));
/*Assemble the full object name for easier wrangling*/
SET @fully_formed_babby =
QUOTENAME(@database_name) +
N'.' +
QUOTENAME(@object_schema) +
N'.' +
QUOTENAME(@object_name);
/*Some sanity checking*/
IF @debug = 1 BEGIN RAISERROR(N'Sanity checking event types', 0, 1) WITH NOWAIT; END;
/* You can only do this right now. */
IF LOWER(@event_type) NOT IN
(
N'waits',
N'blocking',
N'locking',
N'queries',
N'compiles',
N'recompiles',
N'wait',
N'block',
N'blocks',
N'lock',
N'locks',
N'query',
N'compile',
N'recompile',
N'compilation',
N'recompilation',
N'compilations',
N'recompilations'
)
BEGIN
RAISERROR(N'
You have chosen a value for @event_type... poorly. use @help = 1 to see valid arguments.
What on earth is %s?', 11, 1, @event_type) WITH NOWAIT;
RETURN;
END;
IF @debug = 1 BEGIN RAISERROR(N'Checking query sort order', 0, 1) WITH NOWAIT; END;
IF @query_sort_order NOT IN
(
N'cpu',
N'reads',
N'writes',
N'duration',
N'memory',
N'spills',
N'avg cpu',
N'avg reads',
N'avg writes',
N'avg duration',
N'avg memory',
N'avg spills'
)
BEGIN
RAISERROR(N'That sort order (%s) you chose is so out of this world that i''m ignoring it', 0, 1, @query_sort_order) WITH NOWAIT;
SET @query_sort_order = N'avg cpu';
END;
IF @debug = 1 BEGIN RAISERROR(N'Parsing any supplied waits', 0, 1) WITH NOWAIT; END;
SET @wait_type = UPPER(@wait_type);
/* This will hold the CSV list of wait types someone passes in */
INSERT
#user_waits WITH(TABLOCK)
SELECT
wait_type =
LTRIM
(
RTRIM
(
waits.wait_type
)
)
FROM
(
SELECT
wait_type =
x.x.value
(
'(./text())[1]',
'nvarchar(60)'
)
FROM
(
SELECT
wait_type =
CONVERT
(
xml,
N'<x>' +
REPLACE
(
REPLACE
(
@wait_type,
N',',
N'</x><x>'
),
N' ',
N''
) +
N'</x>'
).query(N'.')
) AS w
CROSS APPLY wait_type.nodes(N'x') AS x(x)
) AS waits
WHERE @wait_type <> N'ALL';
/*
If someone is passing in specific waits, let's make sure that
they're valid waits by checking them against what's available.
*/
IF @wait_type <> N'ALL'
BEGIN
IF @debug = 1 BEGIN RAISERROR(N'Checking wait validity', 0, 1) WITH NOWAIT; END;
/* There's no THREADPOOL in XE map values, it gets registered as SOS_WORKER */
SET @wait_type =
REPLACE
(
@wait_type,
N'THREADPOOL',
N'SOS_WORKER'
);
SELECT DISTINCT
invalid_waits =
uw.wait_type
INTO #invalid_waits
FROM #user_waits AS uw
WHERE NOT EXISTS
(
SELECT
1/0
FROM sys.dm_xe_map_values AS dxmv
WHERE dxmv.map_value COLLATE Latin1_General_BIN2 = uw.wait_type COLLATE Latin1_General_BIN2
AND dxmv.name = N'wait_types'
);
/* If we find any invalid waits, let people know */
IF @@ROWCOUNT > 0
BEGIN
SELECT
invalid_waits =
N'You have chosen some invalid wait types'
UNION ALL
SELECT
iw.invalid_waits
FROM #invalid_waits AS iw;
RAISERROR(N'Waidaminnithataintawait', 11, 1) WITH NOWAIT;
RETURN;
END;
END;
/* I just don't want anyone to be disappointed */
IF @debug = 1 BEGIN RAISERROR(N'Avoiding disappointment', 0, 1) WITH NOWAIT; END;
IF
(
@wait_type <> N''
AND @wait_type <> N'ALL'
AND LOWER(@event_type) NOT LIKE N'%wait%'
)
BEGIN
RAISERROR(N'You can''t filter on wait stats unless you use the wait stats event.', 11, 1) WITH NOWAIT;
RETURN;
END;
/* This is probably important, huh? */
IF @debug = 1 BEGIN RAISERROR(N'Are we trying to filter for a blocking session?', 0, 1) WITH NOWAIT; END;
/* blocking events need a database name to resolve objects */
IF
(
LOWER(@event_type) LIKE N'%lock%'
AND DB_ID(@database_name) IS NULL