forked from erikdarlingdata/DarlingData
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsp_PerfCheck.sql
More file actions
4981 lines (4753 loc) · 173 KB
/
sp_PerfCheck.sql
File metadata and controls
4981 lines (4753 loc) · 173 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_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_PerfCheck
@help = 1;
For working through errors:
EXECUTE sp_PerfCheck
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
*/
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 */
@help bit = 0, /*For helpfulness*/
@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';
/*
Help section, for help.
Will become more helpful when out of beta.
*/
IF @help = 1
BEGIN
SELECT
help = N'hello, i am sp_PerfCheck'
UNION ALL
SELECT
help = N'i look at important performance settings and metrics'
UNION ALL
SELECT
help = N'don''t hate me because i''m beautiful.'
UNION ALL
SELECT
help = N'brought to you by erikdarling.com / code.erikdarling.com';
/*
Parameters
*/
SELECT
parameter_name =
ap.name,
data_type =
t.name,
description =
CASE
ap.name
WHEN N'@database_name' THEN 'the name of the database you wish to analyze'
WHEN N'@help' THEN 'displays this help information'
WHEN N'@debug' THEN 'prints debug information during execution'
WHEN N'@version' THEN 'returns the version number of the procedure'
WHEN N'@version_date' THEN 'returns the date this version was released'
ELSE NULL
END,
valid_inputs =
CASE
ap.name
WHEN N'@database_name' THEN 'the name of a database you care about indexes in'
WHEN N'@help' THEN '0 or 1'
WHEN N'@debug' THEN '0 or 1'
WHEN N'@version' THEN 'OUTPUT parameter'
WHEN N'@version_date' THEN 'OUTPUT parameter'
ELSE NULL
END,
defaults =
CASE
ap.name
WHEN N'@database_name' THEN 'NULL'
WHEN N'@help' THEN 'false'
WHEN N'@debug' THEN 'true'
WHEN N'@version' THEN 'NULL'
WHEN N'@version_date' THEN 'NULL'
ELSE NULL
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_PerfCheck'
OPTION(MAXDOP 1, RECOMPILE);
SELECT
mit_license_yo = 'i am MIT licensed, so like, do whatever'
UNION ALL
SELECT
mit_license_yo = 'see printed messages for full license';
RAISERROR('
MIT License
Copyright 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;
/*
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
),
@product_level sysname =
CONVERT
(
sysname,
SERVERPROPERTY(N'ProductLevel')
),
@product_edition sysname =
CONVERT
(
sysname,
SERVERPROPERTY(N'Edition')
),
@server_name sysname =
CONVERT
(
sysname,
SERVERPROPERTY(N'ServerName')
),
@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,
@affinity_mask bigint,
@affinity_io_mask bigint,
@affinity64_mask bigint,
@affinity64_io_mask bigint,
/* 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) = 100.0, /* Threshold for slow reads (ms) */
@slow_write_ms decimal(10, 2) = 100.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) = N'',
@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) = 15.0, /* Alert if more than 15% memory is stolen */
/* 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,
/*SQLDB stuff for IO stats*/
@io_sql nvarchar(max) = N'',
@file_io_sql nvarchar(max) = N'',
@db_size_sql nvarchar(max) = N'',
@tempdb_files_sql nvarchar(max) = N'';
/* Check for VIEW SERVER STATE permission */
IF @is_sysadmin = 0
BEGIN
BEGIN TRY
EXECUTE sys.sp_executesql
N'
SELECT
@has_view_server_state = 1
FROM sys.dm_os_sys_info AS osi;
',
N'@has_view_server_state bit OUTPUT',
@has_view_server_state OUTPUT;
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 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 NOT NULL DEFAULT N'N/A',
object_name sysname NOT NULL DEFAULT N'N/A',
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(260) NULL,
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
);
/* 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')'
);
/* Using server name variable declared earlier */
INSERT INTO
#server_info
(
info_type,
value
)
VALUES
(N'Server Name', @server_name);
/* Using product version and level variables declared earlier */
INSERT INTO
#server_info
(
info_type,
value
)
VALUES
(
N'SQL Server Version',
@product_version +
N' (' +
@product_level +
N')'
);
/* Using product edition variable declared earlier */
INSERT INTO
#server_info
(
info_type,
value
)
VALUES
(N'SQL Server Edition', @product_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 if permissions allow */
IF @has_view_server_state = 1
BEGIN
INSERT INTO
#server_info
(
info_type,
value
)
SELECT
N'Uptime',
CONVERT
(
nvarchar(30),
DATEDIFF
(
DAY,
osi.sqlserver_start_time,
SYSDATETIME()
)
) +
N' days, ' +
CONVERT
(
nvarchar(8),
CONVERT
(
time,
DATEADD
(
SECOND,
DATEDIFF
(
SECOND,
osi.sqlserver_start_time,
SYSDATETIME()
) % 86400,
'00:00:00'
)
),
108
) +
N' (hh:mm:ss)'
FROM sys.dm_os_sys_info AS osi;
END
ELSE
BEGIN
INSERT INTO
#server_info
(
info_type,
value
)
VALUES
(N'Uptime', N'Information unavailable (requires VIEW SERVER STATE permission)');
END;
/* CPU information - works on all platforms if permissions allow */
IF @has_view_server_state = 1
BEGIN
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;
END
ELSE
BEGIN
INSERT INTO
#server_info
(
info_type,
value
)
VALUES
(N'CPU', N'Information unavailable (requires VIEW SERVER STATE permission)');
END;
/* Check for offline schedulers */
IF @azure_sql_db = 0 /* Not applicable to Azure SQL DB */
AND @has_view_server_state = 1 /* Requires VIEW SERVER STATE permission */
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 forced grants - requires VIEW SERVER STATE permission */
IF @has_view_server_state = 1
BEGIN
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 memory grants. ' +
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 */
END;
/* Check for memory grant timeouts - requires VIEW SERVER STATE permission */
IF @has_view_server_state = 1
BEGIN
INSERT INTO
#results
(
check_id,
priority,
category,
finding,
details,
url
)
SELECT
check_id = 4103,
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.timeout_error_count)) +
N' memory grant timeouts. ' +
N'Queries are waiting for memory for a long time and giving up.',
url = N'https://erikdarling.com/sp_PerfCheck#MemoryStarved'
FROM sys.dm_exec_query_resource_semaphores AS ders
WHERE ders.timeout_error_count > 0
HAVING
MAX(ders.timeout_error_count) > 0; /* Only if there are actually forced grants */
END;
/* Check for SQL Server memory dumps (on-prem only) */
IF @azure_sql_db = 0
AND @azure_managed_instance = 0
AND @has_view_server_state = 1 /* Requires sysadmin permission */
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 In Last 90 Days',
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
WHERE dsmd.creation_time >= DATEADD(DAY, -90, SYSDATETIME())
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,
SYSDATETIME()
),
0
)
) > 100
THEN 20 /* Very high priority */
WHEN
(
1.0 *
p.cntr_value /
NULLIF
(
DATEDIFF
(
DAY,
osi.sqlserver_start_time,
SYSDATETIME()
),
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, SYSDATETIME()), 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, SYSDATETIME())) +
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,
SYSDATETIME()
),
0
)
) > 9; /* More than 9 deadlocks per day */
/* Check for large USERSTORE_TOKENPERM (security cache) */