-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathsp_PerfCheck.sql
More file actions
4138 lines (3952 loc) · 155 KB
/
sp_PerfCheck.sql
File metadata and controls
4138 lines (3952 loc) · 155 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 QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.sp_PerfCheck', N'P') IS NULL
BEGIN
EXECUTE(N'CREATE PROCEDURE dbo.sp_PerfCheck AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_PerfCheck
(
@database_name sysname = NULL, /* Database to check, NULL for all user databases */
@debug bit = 0, /* Print diagnostic messages */
@version varchar(30) = NULL OUTPUT, /* Returns version */
@version_date datetime = NULL OUTPUT /* Returns version date */
)
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
/*
Set version information
*/
SELECT
@version = N'1.0.4',
@version_date = N'20250404';
/*
Variable Declarations
*/
DECLARE
@product_version sysname =
CONVERT(sysname, SERVERPROPERTY(N'ProductVersion')),
@product_version_major decimal(10, 2) =
SUBSTRING
(
CONVERT(sysname, SERVERPROPERTY(N'ProductVersion')),
1,
CHARINDEX
(
'.',
CONVERT(sysname, SERVERPROPERTY(N'ProductVersion'))
) + 1
),
@product_version_minor decimal(10, 2) =
PARSENAME
(
CONVERT
(
varchar(32),
CONVERT(sysname, SERVERPROPERTY(N'ProductVersion'))
),
2
),
@engine_edition integer =
CONVERT(integer, SERVERPROPERTY(N'EngineEdition')),
@start_time datetime2(0) = SYSDATETIME(),
@error_message nvarchar(4000) = N'',
@sql nvarchar(MAX) = N'',
@azure_sql_db bit = 0,
@azure_managed_instance bit = 0,
@aws_rds bit = 0,
@is_sysadmin bit =
ISNULL
(
IS_SRVROLEMEMBER(N'sysadmin'),
0
),
@has_view_server_state bit =
/*I'm using this as a shortcut here so I don't have to do anything else later if not sa*/
ISNULL
(
IS_SRVROLEMEMBER(N'sysadmin'),
0
),
@current_database_name sysname,
@current_database_id integer,
@processors integer,
@message nvarchar(4000),
/* Memory configuration variables */
@min_server_memory bigint,
@max_server_memory bigint,
@physical_memory_gb decimal(10, 2),
/* MAXDOP and CTFP variables */
@max_dop integer,
@cost_threshold integer,
/* Other configuration variables */
@priority_boost bit,
@lightweight_pooling bit,
/* TempDB configuration variables */
@tempdb_data_file_count integer,
@tempdb_log_file_count integer,
@min_data_file_size decimal(18, 2),
@max_data_file_size decimal(18, 2),
@size_difference_pct decimal(18, 2),
@has_percent_growth bit,
@has_fixed_growth bit,
/* Storage performance variables */
@slow_read_ms decimal(10, 2) = 20.0, /* Threshold for slow reads (ms) */
@slow_write_ms decimal(10, 2) = 20.0, /* Threshold for slow writes (ms) */
/* Set threshold for "slow" autogrowth (in ms) */
@slow_autogrow_ms integer = 1000, /* 1 second */
@trace_path nvarchar(260),
@autogrow_summary nvarchar(max),
@has_tables bit = 0,
/* Determine total waits, uptime, and significant waits */
@total_waits bigint,
@uptime_ms bigint,
@significant_wait_threshold_pct decimal(5, 2) = 0.5, /* Only waits above 0.5% */
@significant_wait_threshold_avg decimal(10, 2) = 10.0, /* Or avg wait time > 10ms */
/* Threshold settings for stolen memory alert */
@buffer_pool_size_gb decimal(38, 2),
@stolen_memory_gb decimal(38, 2),
@stolen_memory_pct decimal(10, 2),
@stolen_memory_threshold_pct decimal(10, 2) = 25.0, /* Alert if more than 25% memory is stolen */
/* Format the output properly without XML PATH which causes spacing issues */
@wait_summary nvarchar(1000) = N'',
/* CPU scheduling variables */
@signal_wait_time_ms bigint,
@total_wait_time_ms bigint,
@sos_scheduler_yield_ms bigint,
@signal_wait_ratio decimal(10, 2),
@sos_scheduler_yield_pct_of_uptime decimal(10, 2),
/* I/O stalls variables */
@io_stall_summary nvarchar(1000),
/* First check what columns exist in sys.databases to handle version differences */
@has_is_ledger bit = 0,
@has_is_accelerated_database_recovery bit = 0;
/* Check for VIEW SERVER STATE permission */
IF @is_sysadmin = 0
BEGIN
BEGIN TRY
EXECUTE sys.sp_executesql
N'
DECLARE
@c bigint;
SELECT
@c = 1
FROM sys.dm_os_sys_info AS osi;
';
SET @has_view_server_state = 1;
END TRY
BEGIN CATCH
SET @has_view_server_state = 0;
END CATCH;
END;
IF @debug = 1
BEGIN
SELECT
permission_check = N'Permission Check',
is_sysadmin = @is_sysadmin,
has_view_server_state = @has_view_server_state;
END;
/*
Environment Detection
*/
/* Is this Azure SQL DB? */
IF @engine_edition = 5
BEGIN
SET @azure_sql_db = 1;
END;
/* Is this Azure Managed Instance? */
IF @engine_edition = 8
BEGIN
SET @azure_managed_instance = 1;
END;
/* Is this AWS RDS? Only check if not Azure */
IF @azure_sql_db = 0
AND @azure_managed_instance = 0
BEGIN
IF DB_ID('rdsadmin') IS NOT NULL
BEGIN
SET @aws_rds = 1;
END;
END;
IF @debug = 1
BEGIN
SELECT
environment_check = N'Environment Check',
product_version = @product_version,
product_version_major = @product_version_major,
engine_edition = @engine_edition,
is_azure = @azure_sql_db,
is_azure_managed_instance = @azure_managed_instance,
is_aws_rds = @aws_rds;
END;
/*
Create a table for stuff I care about from sys.databases
With comments on what we want to check
*/
CREATE TABLE
#databases
(
name sysname NOT NULL,
database_id integer NOT NULL,
compatibility_level tinyint NOT NULL,
collation_name sysname NOT NULL,
user_access_desc nvarchar(60) NOT NULL,
is_read_only bit NOT NULL,
is_auto_close_on bit NOT NULL,
is_auto_shrink_on bit NOT NULL,
state_desc nvarchar(60) NOT NULL,
snapshot_isolation_state_desc nvarchar(60) NOT NULL,
is_read_committed_snapshot_on bit NOT NULL,
is_auto_create_stats_on bit NOT NULL,
is_auto_create_stats_incremental_on bit NOT NULL,
is_auto_update_stats_on bit NOT NULL,
is_auto_update_stats_async_on bit NOT NULL,
is_ansi_null_default_on bit NOT NULL,
is_ansi_nulls_on bit NOT NULL,
is_ansi_padding_on bit NOT NULL,
is_ansi_warnings_on bit NOT NULL,
is_arithabort_on bit NOT NULL,
is_concat_null_yields_null_on bit NOT NULL,
is_numeric_roundabort_on bit NOT NULL,
is_quoted_identifier_on bit NOT NULL,
is_parameterization_forced bit NOT NULL,
is_query_store_on bit NOT NULL,
is_distributor bit NOT NULL,
is_cdc_enabled bit NOT NULL,
target_recovery_time_in_seconds integer NOT NULL,
delayed_durability_desc nvarchar(60) NOT NULL,
is_accelerated_database_recovery_on bit NOT NULL,
is_ledger_on bit NULL
);
/* Create table for database scoped configurations */
CREATE TABLE
#database_scoped_configs
(
database_id integer NOT NULL,
database_name sysname NOT NULL,
configuration_id integer NOT NULL,
name nvarchar(60) NOT NULL,
value sql_variant NULL,
value_for_secondary sql_variant NULL,
is_value_default bit NOT NULL
);
/*
Create Results Table
*/
CREATE TABLE
#results
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
check_id integer NOT NULL,
priority integer NOT NULL,
category nvarchar(50) NOT NULL,
finding nvarchar(200) NOT NULL,
database_name sysname NULL,
object_name sysname NULL,
details nvarchar(4000) NULL,
url nvarchar(200) NULL
);
/*
Create Server Info Table
*/
CREATE TABLE
#server_info
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
info_type nvarchar(100) NOT NULL,
value nvarchar(4000) NULL
);
/* Create temp table to store TempDB file info */
CREATE TABLE
#tempdb_files
(
file_id integer NOT NULL,
file_name sysname NOT NULL,
type_desc nvarchar(60) NOT NULL,
size_mb decimal(18, 2) NOT NULL,
max_size_mb decimal(18, 2) NOT NULL,
growth_mb decimal(18, 2) NOT NULL,
is_percent_growth bit NOT NULL
);
/* Create temp table for IO stats */
CREATE TABLE
#io_stats
(
database_name sysname NOT NULL,
database_id integer NOT NULL,
file_name sysname NOT NULL,
type_desc nvarchar(60) NOT NULL,
io_stall_read_ms bigint NOT NULL,
num_of_reads bigint NOT NULL,
avg_read_latency_ms decimal(18, 2) NOT NULL,
io_stall_write_ms bigint NOT NULL,
num_of_writes bigint NOT NULL,
avg_write_latency_ms decimal(18, 2) NOT NULL,
io_stall_ms bigint NOT NULL,
total_io bigint NOT NULL,
avg_io_latency_ms decimal(18, 2) NOT NULL,
size_mb decimal(18, 2) NOT NULL,
drive_location nvarchar(255) NULL, /* Changed from drive_letter to handle cloud storage */
physical_name nvarchar(260) NOT NULL
);
/*
Create Database List for Iteration
*/
CREATE TABLE
#database_list
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
database_name sysname NOT NULL,
database_id integer NOT NULL,
state integer NOT NULL,
state_desc nvarchar(60) NOT NULL,
compatibility_level integer NOT NULL,
recovery_model_desc nvarchar(60) NOT NULL,
is_read_only bit NOT NULL,
is_in_standby bit NOT NULL,
is_encrypted bit NOT NULL,
create_date datetime NOT NULL,
can_access bit NOT NULL
);
/* Create a temp table for trace flags */
CREATE TABLE
#trace_flags
(
trace_flag integer NOT NULL,
status integer NOT NULL,
global integer NOT NULL,
session integer NOT NULL
);
/* Create temp table for trace events */
CREATE TABLE
#trace_events
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
event_time datetime NOT NULL,
event_class integer NOT NULL,
event_subclass integer NULL,
event_name sysname NULL,
category_name sysname NULL,
database_name sysname NULL,
database_id integer NULL,
file_name nvarchar(260) NULL,
object_name sysname NULL,
object_type integer NULL,
duration_ms bigint NULL,
severity integer NULL,
success bit NULL,
error integer NULL,
text_data nvarchar(MAX) NULL,
file_growth bigint NULL,
is_auto bit NULL,
spid integer NOT NULL
);
/* Define event class mapping for more readable output */
CREATE TABLE
#event_class_map
(
event_class integer PRIMARY KEY CLUSTERED,
event_name sysname NOT NULL,
category_name sysname NOT NULL
);
/* Create temp table for wait stats */
CREATE TABLE
#wait_stats
(
id integer IDENTITY PRIMARY KEY CLUSTERED,
wait_type nvarchar(60) NOT NULL,
description nvarchar(100) NOT NULL,
wait_time_ms bigint NOT NULL,
wait_time_minutes AS (wait_time_ms / 1000.0 / 60.0),
wait_time_hours AS (wait_time_ms / 1000.0 / 60.0 / 60.0),
waiting_tasks_count bigint NOT NULL,
avg_wait_ms AS (wait_time_ms / NULLIF(waiting_tasks_count, 0)),
percentage decimal(5, 2) NOT NULL,
signal_wait_time_ms bigint NOT NULL,
wait_time_percent_of_uptime decimal(5, 2) NULL,
category nvarchar(50) NOT NULL
);
/* Add wait stats summary to server info - focus on uptime impact */
/* First get top wait categories in a temp table to format properly */
CREATE TABLE
#wait_summary
(
category nvarchar(60) NOT NULL,
pct_of_uptime decimal(10, 2) NOT NULL
);
/* Create temp table for database I/O stalls */
CREATE TABLE
#io_stalls_by_db
(
database_name sysname NOT NULL,
database_id integer NOT NULL,
total_io_stall_ms bigint NOT NULL,
total_io_mb decimal(18, 2) NOT NULL,
avg_io_stall_ms decimal(18, 2) NOT NULL,
read_io_stall_ms bigint NOT NULL,
read_io_mb decimal(18, 2) NOT NULL,
avg_read_stall_ms decimal(18, 2) NOT NULL,
write_io_stall_ms bigint NOT NULL,
write_io_mb decimal(18, 2) NOT NULL,
avg_write_stall_ms decimal(18, 2) NOT NULL,
total_size_mb decimal(18, 2) NOT NULL
);
/*
Collect basic server information (works on all platforms)
*/
IF @debug = 1
BEGIN
RAISERROR('Collecting server information', 0, 1) WITH NOWAIT;
END;
/* Basic server information that works across all platforms */
INSERT INTO
#server_info (info_type, value)
VALUES
(N'sp_PerfCheck', N'Brought to you by Darling Data');
INSERT INTO
#server_info (info_type, value)
VALUES
(N'https://code.erikdarling.com', N'https://erikdarling.com');
INSERT INTO
#server_info (info_type, value)
VALUES
(N'Version', @version + N' (' + CONVERT(varchar(10), @version_date, 101) + N')');
INSERT INTO
#server_info (info_type, value)
VALUES
(N'Server Name', CONVERT(sysname, SERVERPROPERTY(N'ServerName')));
INSERT INTO
#server_info (info_type, value)
VALUES
(
N'SQL Server Version',
CONVERT(sysname, SERVERPROPERTY(N'ProductVersion')) +
N' (' +
CONVERT(sysname, SERVERPROPERTY(N'ProductLevel')) +
N')'
);
INSERT INTO
#server_info (info_type, value)
VALUES
(N'SQL Server Edition', CONVERT(sysname, SERVERPROPERTY(N'Edition')));
/* Environment information - Already detected earlier */
INSERT INTO
#server_info (info_type, value)
SELECT
N'Environment',
CASE
WHEN @azure_sql_db = 1 THEN N'Azure SQL Database'
WHEN @azure_managed_instance = 1 THEN N'Azure SQL Managed Instance'
WHEN @aws_rds = 1 THEN N'AWS RDS SQL Server'
ELSE N'On-premises or IaaS SQL Server'
END;
/* Uptime information - works on all platforms */
INSERT INTO
#server_info (info_type, value)
SELECT
N'Uptime',
CONVERT
(
nvarchar(30),
DATEDIFF(DAY, osi.sqlserver_start_time, GETDATE())
) +
N' days, ' +
CONVERT
(
nvarchar(8),
CONVERT
(
time,
DATEADD
(
SECOND,
DATEDIFF
(
SECOND,
osi.sqlserver_start_time,
GETDATE()
) % 86400,
'00:00:00'
)
),
108
) +
N' (hh:mm:ss)'
FROM sys.dm_os_sys_info AS osi;
/* CPU information - works on all platforms */
INSERT INTO
#server_info (info_type, value)
SELECT
N'CPU',
CONVERT(nvarchar(10), osi.cpu_count) + N' logical processors, ' +
CONVERT(nvarchar(10), osi.hyperthread_ratio) + N' physical cores, ' +
CONVERT(nvarchar(10), ISNULL(osi.numa_node_count, 1)) + N' NUMA node(s)'
FROM sys.dm_os_sys_info AS osi;
/* Check for offline schedulers */
IF @azure_sql_db = 0 /* Not applicable to Azure SQL DB */
BEGIN
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4001,
priority = 20, /* Very high priority */
category = N'CPU Configuration',
finding = N'Offline CPU Schedulers',
details =
CONVERT(nvarchar(10), COUNT_BIG(*)) +
N' CPU scheduler(s) are offline out of ' +
CONVERT(nvarchar(10), (SELECT cpu_count FROM sys.dm_os_sys_info)) +
N' logical processors. This reduces available processing power. ' +
N'Check affinity mask configuration, licensing, or VM CPU cores/sockets',
url = N'https://erikdarling.com/sp_perfcheck/#OfflineCPU'
FROM sys.dm_os_schedulers AS dos
WHERE dos.is_online = 0
HAVING
COUNT_BIG(*) > 0; /* Only if there are offline schedulers */
END;
/* Check for memory-starved queries */
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4101,
priority = 30, /* High priority */
category = N'Memory Pressure',
finding = N'Memory-Starved Queries Detected',
details =
N'dm_exec_query_resource_semaphores has ' +
CONVERT(nvarchar(10), MAX(ders.forced_grant_count)) +
N' forced grants. ' +
N'Target memory: ' + CONVERT(nvarchar(20), MAX(ders.target_memory_kb) / 1024 / 1024) +
N' GB, ' +
N'Available memory: ' + CONVERT(nvarchar(20), MAX(ders.available_memory_kb) / 1024 / 1024) +
N' GB, ' +
N'Granted memory: ' + CONVERT(nvarchar(20), MAX(ders.granted_memory_kb) / 1024 / 1024) +
N' GB. ' +
N'Queries are being forced to run with less memory than requested, which can cause spills to tempdb and poor performance.',
url = N'https://erikdarling.com/sp_PerfCheck#MemoryStarved'
FROM sys.dm_exec_query_resource_semaphores AS ders
WHERE ders.forced_grant_count > 0
HAVING
MAX(ders.forced_grant_count) > 0; /* Only if there are actually forced grants */
/* Check for SQL Server memory dumps (on-prem only) */
IF @azure_sql_db = 0
AND @azure_managed_instance = 0
BEGIN
/* First check if the DMV exists (SQL 2008+) */
IF OBJECT_ID('sys.dm_server_memory_dumps') IS NOT NULL
BEGIN
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4102,
priority = 20, /* Very high priority */
category = N'Server Stability',
finding = N'Memory Dumps Detected',
details =
CONVERT(nvarchar(10), COUNT_BIG(*)) +
N' memory dump(s) found. Most recent: ' +
CONVERT(nvarchar(30), MAX(dsmd.creation_time), 120) +
N', ' +
N' at ' +
MAX(dsmd.filename) +
N'. Check the SQL Server error log and Windows event logs.',
url = N'https://erikdarling.com/sp_PerfCheck#MemoryDumps'
FROM sys.dm_server_memory_dumps AS dsmd
HAVING
COUNT_BIG(*) > 0; /* Only if there are memory dumps */
END;
END;
/* Check for high number of deadlocks */
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4103,
priority =
CASE
WHEN (1.0 * p.cntr_value / NULLIF(DATEDIFF(DAY, osi.sqlserver_start_time, GETDATE()), 0)) > 100
THEN 20 /* Very high priority */
WHEN (1.0 * p.cntr_value / NULLIF(DATEDIFF(DAY, osi.sqlserver_start_time, GETDATE()), 0)) > 50
THEN 30 /* High priority */
ELSE 40 /* Medium-high priority */
END,
category = N'Concurrency',
finding = N'High Number of Deadlocks',
details =
N'Server is averaging ' +
CONVERT(nvarchar(20), CONVERT(decimal(10, 2), 1.0 * p.cntr_value /
NULLIF(DATEDIFF(DAY, osi.sqlserver_start_time, GETDATE()), 0))) +
N' deadlocks per day since startup (' +
CONVERT(nvarchar(20), p.cntr_value) + ' total deadlocks over ' +
CONVERT(nvarchar(10), DATEDIFF(DAY, osi.sqlserver_start_time, GETDATE())) +
N' days). ' +
N'High deadlock rates indicate concurrency issues that should be investigated.',
url = N'https://erikdarling.com/sp_PerfCheck#Deadlocks'
FROM sys.dm_os_performance_counters AS p
CROSS JOIN sys.dm_os_sys_info AS osi
WHERE RTRIM(p.counter_name) = N'Number of Deadlocks/sec'
AND RTRIM(p.instance_name) = N'_Total'
AND p.cntr_value > 0
AND
(
1.0 * p.cntr_value /
NULLIF
(
DATEDIFF
(
DAY,
osi.sqlserver_start_time,
GETDATE()
),
0
)
) > 9; /* More than 9 deadlocks per day */
/* Check for large USERSTORE_TOKENPERM (security cache) */
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4104,
priority =
CASE
WHEN CONVERT(decimal(10, 2), (domc.pages_kb / 1024.0 / 1024.0)) > 5
THEN 20 /* Very high priority >5GB */
WHEN CONVERT(decimal(10, 2), (domc.pages_kb / 1024.0 / 1024.0)) > 2
THEN 30 /* High priority >2GB */
WHEN CONVERT(decimal(10, 2), (domc.pages_kb / 1024.0 / 1024.0)) > 1
THEN 40 /* Medium-high priority >1GB */
ELSE 50 /* Medium priority */
END,
category = N'Memory Usage',
finding = N'Large Security Token Cache',
details =
N'TokenAndPermUserStore cache size is ' +
CONVERT(nvarchar(20), CONVERT(decimal(10, 2), (domc.pages_kb / 1024.0 / 1024.0))) +
N' GB. Large security caches can consume significant memory and may indicate security-related issues ' +
N'such as excessive application role usage or frequent permission changes. ' +
N'Consider using dbo.ClearTokenPerm stored procedure to manage this issue.',
url = N'https://erikdarling.com/sp_PerfCheck#SecurityToken'
FROM sys.dm_os_memory_clerks AS domc
WHERE domc.type = N'USERSTORE_TOKENPERM'
AND domc.name = N'TokenAndPermUserStore'
AND domc.pages_kb >= 500000; /* Only if bigger than 500MB */
/* Check if Lock Pages in Memory is enabled (on-prem and managed instances only) */
IF @azure_sql_db = 0
AND @has_view_server_state = 1
BEGIN
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4105,
priority = 50, /* Medium priority */
category = N'Memory Configuration',
finding = N'Lock Pages in Memory Not Enabled',
details =
N'SQL Server is not using locked pages in memory (LPIM). This can lead to Windows ' +
N'taking memory away from SQL Server under memory pressure, causing performance issues. ' +
N'For production SQL Servers with more than 64GB of memory, LPIM should be enabled.',
url = N'https://erikdarling.com/sp_PerfCheck#LPIM'
FROM sys.dm_os_sys_info AS osi
WHERE osi.sql_memory_model_desc = N'CONVENTIONAL' /* Conventional means not using LPIM */
AND @physical_memory_gb >= 32 /* Only recommend for servers with >=32GB RAM */;
END;
/* Check if Instant File Initialization is enabled (on-prem and managed instances only) */
IF @azure_sql_db = 0
AND @has_view_server_state = 1
BEGIN
INSERT INTO
#server_info (info_type, value)
SELECT
N'Instant File Initialization',
CASE
WHEN dss.instant_file_initialization_enabled = N'Y'
THEN N'Enabled'
ELSE N'Disabled'
END
FROM sys.dm_server_services AS dss
WHERE dss.filename LIKE N'%sqlservr.exe%'
AND dss.servicename LIKE N'SQL Server%';
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT TOP (1)
check_id = 4106,
priority = 50, /* Medium priority */
category = N'Storage Configuration',
finding = N'Instant File Initialization Disabled',
details =
N'Instant File Initialization is not enabled. This can significantly slow down database file ' +
N'creation and growth operations, as SQL Server must zero out data files before using them. ' +
N'Enable this feature by granting the "Perform Volume Maintenance Tasks" permission to the SQL Server service account.',
url = N'https://erikdarling.com/sp_PerfCheck#IFI'
FROM sys.dm_server_services AS dss
WHERE dss.filename LIKE N'%sqlservr.exe%'
AND dss.servicename LIKE N'SQL Server%'
AND dss.instant_file_initialization_enabled = N'N';
END;
/* Check if Resource Governor is enabled */
IF @has_view_server_state = 1
BEGIN
/* First, add Resource Governor status to server info */
IF EXISTS (SELECT 1/0 FROM sys.resource_governor_configuration AS rgc WHERE rgc.is_enabled = 1)
BEGIN
INSERT INTO
#server_info (info_type, value)
SELECT
N'Resource Governor',
N'Enabled';
/* Add informational message about Resource Governor with query suggestion */
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4107,
priority = 50, /* Medium priority */
category = N'Resource Governor',
finding = N'Resource Governor Enabled',
details =
N'Resource Governor is enabled on this instance. This affects workload resource allocation and may ' +
N'impact performance by limiting resources available to various workloads. ' +
N'For more details, run these queries to explore your configuration:' + NCHAR(13) + NCHAR(10) + NCHAR(13) + NCHAR(10) +
N'/* Resource Governor configuration */' + NCHAR(13) + NCHAR(10) +
N'SELECT * FROM sys.resource_governor_configuration;' + NCHAR(13) + NCHAR(10) + NCHAR(13) + NCHAR(10) +
N'/* Resource pools and their settings */' + NCHAR(13) + NCHAR(10) +
N'SELECT * FROM sys.dm_resource_governor_resource_pools;' + NCHAR(13) + NCHAR(10) + NCHAR(13) + NCHAR(10) +
N'/* Workload groups and their settings */' + NCHAR(13) + NCHAR(10) +
N'SELECT * FROM sys.dm_resource_governor_workload_groups;' + NCHAR(13) + NCHAR(10) + NCHAR(13) + NCHAR(10) +
N'/* Classifier function (if configured) */' + NCHAR(13) + NCHAR(10) +
N'SELECT * FROM sys.resource_governor_configuration ' + NCHAR(13) + NCHAR(10) +
N'CROSS APPLY (SELECT OBJECT_NAME(classifier_function_id) AS classifier_function_name) AS cf;',
url = N'https://erikdarling.com/sp_PerfCheck#ResourceGovernor'
FROM sys.resource_governor_configuration AS rgc
WHERE rgc.is_enabled = 1;
END
ELSE
BEGIN
INSERT INTO
#server_info (info_type, value)
SELECT
N'Resource Governor',
N'Disabled';
END;
END;
/* Check for globally enabled trace flags (not in Azure) */
IF @azure_sql_db = 0
AND @azure_managed_instance = 0
BEGIN
/* Capture trace flags */
INSERT INTO
#trace_flags
EXECUTE sys.sp_executesql
N'DBCC TRACESTATUS WITH NO_INFOMSGS';
/* Add trace flags to server info */
IF EXISTS (SELECT 1/0 FROM #trace_flags AS tf WHERE tf.global = 1)
BEGIN
INSERT INTO
#server_info (info_type, value)
SELECT
N'Global Trace Flags',
STUFF
(
(
SELECT
N', ' +
CONVERT(varchar(10), tf.trace_flag)
FROM #trace_flags AS tf
WHERE tf.global = 1
ORDER BY
tf.trace_flag
FOR
XML
PATH('')
),
1,
2,
N''
);
END;
END;
/* Memory information - works on all platforms */
INSERT INTO
#server_info (info_type, value)
SELECT
N'Memory',
N'Total: ' +
CONVERT(nvarchar(20), CONVERT(decimal(10, 2), osi.physical_memory_kb / 1024.0 / 1024.0)) +
N' GB, ' +
N'Target: ' +
CONVERT(nvarchar(20), CONVERT(decimal(10, 2), osi.committed_target_kb / 1024.0 / 1024.0)) +
N' GB' +
N', ' +
osi.sql_memory_model_desc +
N' enabled'
FROM sys.dm_os_sys_info AS osi;
/* Check for important events in default trace (Windows only for now) */
IF @azure_sql_db = 0
BEGIN
/* Get default trace path */
SELECT
@trace_path =
REVERSE
(
SUBSTRING
(
REVERSE(t.path),
CHARINDEX
(
CHAR(92),
REVERSE(t.path)
),
260
)
) + N'log.trc'
FROM sys.traces AS t
WHERE t.is_default = 1;
IF @trace_path IS NOT NULL
BEGIN
/* Insert common event classes we're interested in */
INSERT INTO
#event_class_map (event_class, event_name, category_name)
VALUES
(92, N'Data File Auto Grow', N'Database'),
(93, N'Log File Auto Grow', N'Database'),
(94, N'Data File Auto Shrink', N'Database'),
(95, N'Log File Auto Shrink', N'Database'),
(116, N'DBCC Event', N'Database'),
(137, N'Server Memory Change', N'Server');
/* Get relevant events from default trace */
INSERT INTO
#trace_events
(
event_time,
event_class,
event_subclass,
database_name,
database_id,
file_name,
object_name,
object_type,
duration_ms,
severity,
success,
error,
text_data,
file_growth,
is_auto,
spid
)
SELECT
event_time = t.StartTime,
event_class = t.EventClass,
event_subclass = t.EventSubClass,
database_name = DB_NAME(t.DatabaseID),
database_id = t.DatabaseID,
file_name = t.FileName,
object_name = t.ObjectName,
object_type = t.ObjectType,
duration_ms = t.Duration / 1000, /* Duration is in microseconds, convert to ms */
severity = t.Severity,
success = t.Success,
error = t.Error,
text_data = t.TextData,
file_growth = t.IntegerData, /* Size of growth in Data/Log Auto Grow event */
is_auto = t.IsSystem,
spid = t.SPID
FROM sys.fn_trace_gettable(@trace_path, DEFAULT) AS t
WHERE
/* Auto-grow and auto-shrink events */
t.EventClass IN (92, 93, 94, 95)
/* DBCC Events */
OR
(
t.EventClass = 116
AND
(
t.TextData LIKE N'%FREEPROCCACHE%'
OR t.TextData LIKE N'%FREESYSTEMCACHE%'
OR t.TextData LIKE N'%DROPCLEANBUFFERS%'
OR t.TextData LIKE N'%SHRINKDATABASE%'
OR t.TextData LIKE N'%SHRINKFILE%'
)
)
/* Server memory change events */
OR t.EventClass = 137
/* Deadlock events - typically not in default trace but including for completeness */
OR t.EventClass = 148
/* Look back at the past 7 days of events at most */
AND t.StartTime > DATEADD(DAY, -7, GETDATE());
/* Update event names from map */
UPDATE
te
SET