-
Notifications
You must be signed in to change notification settings - Fork 8
/
sp_Develop.sql
2854 lines (2615 loc) · 184 KB
/
sp_Develop.sql
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
IF OBJECT_ID('dbo.sp_Develop') IS NULL
BEGIN
EXEC dbo.sp_executesql @stmt = N'CREATE PROCEDURE dbo.sp_Develop AS BEGIN SET NOCOUNT ON; END';
END;
GO
ALTER PROCEDURE dbo.sp_Develop
@DatabaseName nvarchar(128) = NULL /*Defaults to current DB if not specified*/
,@GetAllDatabases bit = 0
,@BringThePain bit = 0
,@SkipCheckServer nvarchar(128) = NULL
,@SkipCheckDatabase nvarchar(128) = NULL
,@SkipCheckSchema nvarchar(128) = NULL
,@SkipCheckTable nvarchar(128) = NULL
,@OutputType varchar(20) = 'TABLE'
,@ShowSummary bit = 0
,@PriorityOrHigher varchar(8) = NULL /* Critical, High, Medium, Low, or NULL */
,@RunCheckIds varchar(MAX) = NULL /* Pass a comma delimited list of CheckIds like 1,2,3 if you only need a limited number of checks to run */
,@Debug int = 0
,@Version varchar(30) = NULL OUTPUT
,@VersionDate datetime = NULL OUTPUT
,@VersionCheckMode bit = 0
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
/**********************************************************************************************************************
** MIT License
**
** Copyright for portions of sp_Develop are held by Brent Ozar Unlimited as part of project
** SQL-Server-First-Responder-Kit and are provided under the MIT license:
** https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/
**
** Copyright for portions of sp_Develop are held by Phil Factor (real name withheld) as part of project
** SQLCodeSmells https://github.com/Phil-Factor/SQLCodeSmells
**
** All other copyrights for sp_Develop are held by Emergent Software, LLC as described below.
**
** Copyright (c) 2023 Emergent Software, LLC
**
** 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.
**********************************************************************************************************************/
/**********************************************************************************************************************
** Declare some varibles
**********************************************************************************************************************/
DECLARE
@LineFeed nvarchar(5)
,@NumDatabases int
,@Message nvarchar(4000)
,@StringToExecute nvarchar(MAX)
,@ScriptVersionName nvarchar(50)
,@ErrorSeverity int
,@ErrorState int
,@DatabaseId int
,@CheckId int
,@FindingGroup varchar(100)
,@Finding varchar(200)
,@URLBase varchar(120)
,@URLSkipChecks varchar(100)
,@URLAnchor varchar(400)
,@Priority int
,@ProductVersion nvarchar(128)
,@ProductVersionMajor decimal(10, 2)
,@ProductVersionMinor decimal(10, 2);
/**********************************************************************************************************************
** Setting some varibles
**********************************************************************************************************************/
SET @Version = '2.1.1';
SET @VersionDate = '20230513';
SET @URLBase = 'https://emergentsoftware.github.io/SQL-Server-Development-Assessment/best-practices-and-potential-findings/';
SET @URLSkipChecks = 'https://emergentsoftware.github.io/SQL-Server-Development-Assessment/how-to-skip-checks';
SET @OutputType = UPPER(@OutputType);
SET @LineFeed = CHAR(13) + CHAR(10);
SET @ScriptVersionName = N'sp_Develop v' + @Version + N' - ' + DATENAME(MONTH, @VersionDate) + N' ' + RIGHT('0' + DATENAME(DAY, @VersionDate), 2) + N', ' + DATENAME(YEAR, @VersionDate);
SET @ProductVersion = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(128));
SET @ProductVersionMajor = SUBSTRING(@ProductVersion, 1, CHARINDEX('.', @ProductVersion) + 1);
SET @ProductVersionMinor = PARSENAME(CONVERT(varchar(32), @ProductVersion), 2);
IF @VersionCheckMode = 1
BEGIN
RETURN;
END;
IF @Debug IN (1, 2)
BEGIN
RAISERROR(N'Starting run. %s', 0, 1, @ScriptVersionName) WITH NOWAIT;
END;
/**********************************************************************************************************************
** We start by creating #Finding. It's a temp table that will store all of the results from our checks.
** Throughout the rest of this stored procedure, we're running a series of checks looking for issues inside the
** database. When we find a problem, we insert rows into #Finding. At the end, we return these results to the
** end user.
**
** #Finding has a CheckId field, but there's no Check table. As we do checks, we insert data into this table,
** and we manually put in the CheckId.
**
** Create other temp tables
**********************************************************************************************************************/
IF OBJECT_ID('tempdb..#Finding') IS NOT NULL
BEGIN
DROP TABLE #Finding;
END;
CREATE TABLE #Finding (
DeveloperResultsId int IDENTITY(1, 1) NOT NULL
,CheckId int NOT NULL DEFAULT-1
,Database_Id int NOT NULL DEFAULT-1
,DatabaseName nvarchar(128) NOT NULL DEFAULT N''
,Priority int NOT NULL DEFAULT-1
,FindingGroup varchar(100) NOT NULL
,Finding varchar(200) NOT NULL
,URL varchar(2047) NOT NULL
,Details nvarchar(4000) NOT NULL
,Schema_Id int NOT NULL DEFAULT-1
,SchemaName nvarchar(128) NULL DEFAULT N''
,Object_Id int NOT NULL DEFAULT-1
,ObjectName nvarchar(128) NOT NULL DEFAULT N''
,ObjectType nvarchar(60) NOT NULL DEFAULT N''
);
IF OBJECT_ID('tempdb..#DatabaseList') IS NOT NULL
BEGIN
DROP TABLE #DatabaseList;
END;
CREATE TABLE #DatabaseList (
DatabaseName nvarchar(256) NOT NULL
,secondary_role_allow_connections_desc nvarchar(50) NULL DEFAULT 'YES'
);
IF OBJECT_ID('tempdb..#DatabaseIgnore') IS NOT NULL
BEGIN
DROP TABLE #DatabaseIgnore;
END;
CREATE TABLE #DatabaseIgnore (DatabaseName nvarchar(128) NOT NULL, Reason nvarchar(100) NOT NULL);
IF OBJECT_ID('tempdb..#SkipCheck') IS NOT NULL
BEGIN
DROP TABLE #SkipCheck;
END;
CREATE TABLE #SkipCheck (
ServerName nvarchar(128) NULL
,DatabaseName nvarchar(128) NULL
,SchemaName nvarchar(128) NULL
,ObjectName nvarchar(128) NULL
,CheckId int NULL
);
CREATE CLUSTERED INDEX CheckId_DatabaseName ON #SkipCheck (CheckId, DatabaseName);
/**********************************************************************************************************************
** Skip Checks or Run Checks
**********************************************************************************************************************/
/* If there is a value then skip all other checks except what is passed in */
IF @RunCheckIds IS NOT NULL
BEGIN
/* Create temporary table to store the RunCheckIds rows */
IF OBJECT_ID('tempdb..#RunCheckIds') IS NOT NULL
BEGIN
DROP TABLE #RunCheckIds;
END;
CREATE TABLE #RunCheckIds (CheckId int NOT NULL);
INSERT INTO #RunCheckIds (CheckId)
SELECT
CheckId = CheckIds.value('.', 'BIGINT')
FROM (
SELECT
CheckId = CAST('<Items><item>' + REPLACE(@RunCheckIds, ',', '</item><item>') + '</item></Items> ' AS xml)
) AS CheckIdsXML
CROSS APPLY CheckId.nodes('/Items/item') AS C(CheckIds);
/* Create temporary table to store the PossibleCheckIds */
IF OBJECT_ID('tempdb..#PossibleCheckIds') IS NOT NULL
BEGIN
DROP TABLE #PossibleCheckIds;
END;
CREATE TABLE #PossibleCheckIds (CheckId int NOT NULL);
INSERT INTO #PossibleCheckIds (CheckId)
SELECT TOP (10000)
CheckId = ROW_NUMBER() OVER (ORDER BY O1.object_id)
FROM
sys.objects AS O1
CROSS JOIN sys.objects AS O2;
INSERT INTO #SkipCheck (ServerName, DatabaseName, SchemaName, ObjectName, CheckId)
SELECT NULL, NULL, NULL, NULL, CheckId FROM #PossibleCheckIds
EXCEPT
SELECT NULL, NULL, NULL, NULL, CheckId FROM #RunCheckIds
ORDER BY
CheckId ASC;
END;
ELSE
BEGIN
IF (@SkipCheckTable IS NOT NULL AND RTRIM(LTRIM(@SkipCheckTable)) <> '')
AND (@SkipCheckSchema IS NOT NULL AND RTRIM(LTRIM(@SkipCheckSchema)) <> '')
AND (@SkipCheckDatabase IS NOT NULL AND RTRIM(LTRIM(@SkipCheckDatabase)) <> '')
BEGIN
IF @Debug IN (1, 2)
RAISERROR('Inserting SkipChecks', 0, 1) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#SkipCheck(ServerName, DatabaseName, SchemaName, ObjectName, CheckId)
SELECT
SK.ServerName
,SK.DatabaseName
,SK.SchemaName
,SK.ObjectName
,SK.CheckId
FROM ' ;
IF LTRIM(RTRIM(@SkipCheckServer)) <> ''
BEGIN
SET @StringToExecute = @StringToExecute + QUOTENAME(@SkipCheckServer) + N'.';
END;
SET @StringToExecute = @StringToExecute + QUOTENAME(@SkipCheckDatabase) + N'.' + QUOTENAME(@SkipCheckSchema) + N'.' + QUOTENAME(@SkipCheckTable) + N' AS SK
WHERE
SK.ServerName IS NULL
OR SK.ServerName = SERVERPROPERTY(''ServerName'')
GROUP BY
SK.ServerName
,SK.DatabaseName
,SK.SchemaName
,SK.ObjectName
,SK.CheckId
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2
AND @StringToExecute IS NOT NULL
PRINT @StringToExecute;
/* Check if we should be running checks on this server, exit out if not. */
IF EXISTS (
SELECT
*
FROM
#SkipCheck AS SC
WHERE
SC.ServerName = SERVERPROPERTY('ServerName')
AND SC.DatabaseName IS NULL
AND SC.ObjectName IS NULL
)
BEGIN
IF @Debug IN (1, 2)
RAISERROR('The SQL Server is marked to be skipped', 0, 1) WITH NOWAIT;
RETURN;
END;
IF @Debug IN (1, 2)
RAISERROR('The SQL Server is not marked to be skipped', 0, 1) WITH NOWAIT;
END;
END;
/**********************************************************************************************************************
** Skip checks for specific SQL Servers
**********************************************************************************************************************/
/* If the server is Amazon RDS, skip checks that it doesn't allow */
IF LEFT(CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS varchar(8000)), 8) = 'EC2AMAZ-'
AND LEFT(CAST(SERVERPROPERTY('MachineName') AS varchar(8000)), 8) = 'EC2AMAZ-'
AND LEFT(CAST(SERVERPROPERTY('ServerName') AS varchar(8000)), 8) = 'EC2AMAZ-'
AND DB_ID('rdsadmin') IS NOT NULL
AND EXISTS (
SELECT
*
FROM
sys.all_objects
WHERE
name IN ('rds_startup_tasks', 'rds_help_revlogin', 'rds_hexadecimal', 'rds_failover_tracking', 'rds_database_tracking', 'rds_track_change')
)
BEGIN
/* Check to skip go here */
/* INSERT INTO #SkipCheck (CheckId) VALUES (?); */
/* Let them know we are skipping checks */
INSERT INTO #Finding (CheckId, FindingGroup, Finding, URL, Details)
SELECT
CheckID = 26
,FindingGroup = 'Running Issues'
,Finding = 'Some Checks Skipped'
,URL = @URLBase + 'running-issues#some-checks-skipped'
,Details = 'Amazon RDS detected, so we skipped some checks that are not currently possible, relevant, or practical there.';
END;
/* If the server is Express Edition, skip checks that it doesn't allow */
IF CAST(SERVERPROPERTY('Edition') AS nvarchar(1000)) LIKE N'%Express%'
BEGIN
/* Check to skip go here */
/* INSERT INTO #SkipCheck (CheckId) VALUES (?); */
/* Let them know we are skipping checks */
INSERT INTO #Finding (CheckId, FindingGroup, Finding, URL, Details)
SELECT
CheckID = 26
,FindingGroup = 'Running Issues'
,Finding = 'Some Checks Skipped'
,URL = @URLBase + 'running-issues#some-checks-skipped'
,Details = 'Express Edition detected, so we skipped some checks that are not currently possible, relevant, or practical there.';
END;
/* If the server is an Azure Managed Instance, skip checks that it doesn't allow */
IF SERVERPROPERTY('EngineEdition') = 8
BEGIN
/* Check to skip go here */
/* INSERT INTO #SkipCheck (CheckId) VALUES (?); */
/* Let them know we are skipping checks */
INSERT INTO #Finding (CheckId, FindingGroup, Finding, URL, Details)
SELECT
CheckID = 26
,FindingGroup = 'Running Issues'
,Finding = 'Some Checks Skipped'
,URL = @URLBase + 'running-issues#some-checks-skipped'
,Details = 'Managed Instance detected, so we skipped some checks that are not currently possible, relevant, or practical there.';
END;
/**********************************************************************************************************************
** What databases are we going to ignore?
**********************************************************************************************************************/
INSERT INTO #DatabaseIgnore (DatabaseName, Reason)
SELECT
SC.DatabaseName
,N'Included in skip checks'
FROM
#SkipCheck AS SC
WHERE
(SC.ServerName = SERVERPROPERTY('ServerName') OR SC.ServerName IS NULL)
AND SC.ObjectName IS NULL
AND SC.CheckId IS NULL
AND SC.DatabaseName IS NOT NULL
OPTION (RECOMPILE);
/**********************************************************************************************************************
** What databases are we going to check?
**********************************************************************************************************************/
IF @GetAllDatabases = 1
BEGIN
INSERT INTO #DatabaseList (DatabaseName)
SELECT
DB_NAME(database_id)
FROM
sys.databases
WHERE
user_access_desc = N'MULTI_USER'
AND state_desc = N'ONLINE'
AND database_id > 4
AND DB_NAME(database_id)NOT LIKE N'ReportServer%' /* SQL Server Reporting Services */
AND DB_NAME(database_id)NOT LIKE N'rdsadmin%' /* Amazon RDS default database */
AND DB_NAME(database_id) NOT IN (N'DWQueue', N'DWDiagnostics', N'DWConfiguration') /* PolyBase databases do not need to be checked */
AND DB_NAME(database_id) NOT IN (N'SSISDB') /* SQL Server Integration Services */
AND is_distributor = 0
OPTION (RECOMPILE);
/* Skip non-readable databases in an AG */
IF EXISTS (
SELECT
*
FROM
sys.all_objects AS O
INNER JOIN sys.all_columns AS C
ON O.object_id = C.object_id
AND O.name = 'dm_hadr_availability_replica_states'
AND C.name = 'role_desc'
)
BEGIN
SET @StringToExecute = N'
UPDATE
DL
SET
secondary_role_allow_connections_desc = ''NO''
FROM
#DatabaseList AS DL
INNER JOIN sys.databases AS D ON DL.DatabaseName = D.name
INNER JOIN sys.dm_hadr_availability_replica_states AS RS ON D.replica_id = RS.replica_id
INNER JOIN sys.availability_replicas AS R ON RS.replica_id = R.replica_id
WHERE
RS.role_desc = ''SECONDARY''
AND R.secondary_role_allow_connections_desc = ''NO''
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF EXISTS (
SELECT
*
FROM
#DatabaseList
WHERE
secondary_role_allow_connections_desc = N'NO'
)
BEGIN
/**********************************************************************************************************************/
SELECT
@CheckId = 17
,@Priority = 1
,@FindingGroup = 'Running Issues'
,@Finding = 'You are running this on an AG secondary, and some of your databases are configured as non-readable when this is a secondary node.'
,@URLAnchor = 'running-issues#17';
/**********************************************************************************************************************/
INSERT INTO #Finding (CheckId, FindingGroup, Finding, URL, Priority, Details)
SELECT
CheckId = @CheckId
,FindingGroup = @FindingGroup
,Finding = @Finding
,URL = @URLBase + @URLAnchor
,Priority = @Priority
,Details = N'To analyze those databases, run sp_Develop on the primary, or on a readable secondary.';
END;
END;
END;
ELSE
BEGIN
INSERT INTO #DatabaseList (DatabaseName)
SELECT
CASE WHEN @DatabaseName IS NULL OR @DatabaseName = N'' THEN DB_NAME()ELSE @DatabaseName END;
END;
SET @NumDatabases = (
SELECT
COUNT(*)
FROM
#DatabaseList AS DL
LEFT OUTER JOIN #DatabaseIgnore AS I
ON DL.DatabaseName = I.DatabaseName
WHERE
COALESCE(DL.secondary_role_allow_connections_desc, 'OK') <> 'NO'
AND I.DatabaseName IS NULL
);
SET @Message = N'Number of databases to examine: ' + CAST(@NumDatabases AS nvarchar(50));
IF @Debug IN (1, 2)
RAISERROR(@Message, 0, 1) WITH NOWAIT;
/**********************************************************************************************************************/
SELECT
@CheckId = 18
,@Priority = 1
,@FindingGroup = 'Running Issues'
,@Finding = 'Ran Against 50+ Databases Without @BringThePain = 1'
,@URLAnchor = 'running-issues#18';
/**********************************************************************************************************************/
BEGIN TRY
IF @NumDatabases >= 50
AND @BringThePain <> 1
BEGIN
INSERT #Finding (CheckId, FindingGroup, Finding, URL, Priority, Details)
SELECT
CheckId = @CheckId
,FindingGroup = @FindingGroup
,Finding = @Finding
,URL = @URLBase + @URLAnchor
,Priority = @Priority
,Details = N'You''re trying to run sp_Develop on a server with ' + CAST(@NumDatabases AS nvarchar(50)) + ' databases. If you''re sure you want to do this, run again with the parameter @BringThePain = 1.';
IF (@OutputType <> 'NONE')
BEGIN
SELECT
DR.DatabaseName
,DR.SchemaName
,DR.ObjectName
,DR.ObjectType
,DR.FindingGroup
,DR.Finding
,DR.Details
,DR.URL
,DR.CheckId
,DR.Database_Id
,DR.Schema_Id
,DR.Object_Id
,DR.Priority
FROM
#Finding AS DR
ORDER BY
DR.Priority
,DR.DatabaseName
,DR.SchemaName
,DR.ObjectName
,DR.FindingGroup
,DR.Finding
OPTION (RECOMPILE);
RAISERROR('Running sp_Develop on a server with 50+ databases may cause temporary insanity for the server', 12, 1);
END;
RETURN;
END;
END TRY
BEGIN CATCH
RAISERROR(N'Failure to execute due to number of databases.', 0, 1) WITH NOWAIT;
SELECT
@Message = ERROR_MESSAGE()
,@ErrorSeverity = ERROR_SEVERITY()
,@ErrorState = ERROR_STATE();
RAISERROR(@Message, @ErrorSeverity, @ErrorState);
WHILE @@TRANCOUNT > 0
ROLLBACK;
RETURN;
END CATCH;
/**********************************************************************************************************************/
SELECT
@CheckId = 16
,@Priority = 1
,@FindingGroup = 'Running Issues'
,@Finding = 'sp_Develop is Over 6 Months Old'
,@URLAnchor = 'running-issues#16';
/**********************************************************************************************************************/
IF NOT EXISTS (
SELECT
1
FROM
#SkipCheck AS SC
WHERE
SC.CheckId = @CheckId
AND SC.ObjectName IS NULL
)
AND DATEDIFF(MONTH, @VersionDate, GETDATE()) > 6
BEGIN
IF @Debug IN (1, 2)
RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
INSERT #Finding (CheckId, FindingGroup, Finding, URL, Priority, Details)
SELECT
CheckId = @CheckId
,FindingGroup = @FindingGroup
,Finding = @Finding
,URL = @URLBase + @URLAnchor
,Priority = @Priority
,Details = N'There most likely been some new checks and fixes performed within the last 6 months - time to go download the current one.';
END;
/**********************************************************************************************************************
** Starting loop through databases
**********************************************************************************************************************/
IF @Debug IN (1, 2)
RAISERROR(N'Starting loop through databases', 0, 1) WITH NOWAIT;
DECLARE database_cursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
DL.DatabaseName
FROM
#DatabaseList AS DL
LEFT OUTER JOIN #DatabaseIgnore AS I
ON DL.DatabaseName = I.DatabaseName
WHERE
COALESCE(DL.secondary_role_allow_connections_desc, 'OK') <> 'NO'
AND I.DatabaseName IS NULL
OPTION (RECOMPILE);
OPEN database_cursor;
FETCH NEXT FROM database_cursor
INTO
@DatabaseName;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Debug IN (1, 2)
BEGIN
RAISERROR(@LineFeed, 0, 1) WITH NOWAIT;
RAISERROR(@LineFeed, 0, 1) WITH NOWAIT;
RAISERROR(@DatabaseName, 0, 1) WITH NOWAIT;
END;
SELECT
@DatabaseId = database_id
FROM
sys.databases
WHERE
name = @DatabaseName
AND user_access_desc = 'MULTI_USER'
AND state_desc = 'ONLINE'
OPTION (RECOMPILE);
/**********************************************************************************************************************
** ██████ ██ ██ ███████ ██████ ██ ██ ███████ ███████ ████████ █████ ██████ ████████
** ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
** ██ ███████ █████ ██ █████ ███████ ███████ ██ ███████ ██████ ██
** ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
** ██████ ██ ██ ███████ ██████ ██ ██ ███████ ███████ ██ ██ ██ ██ ██ ██
**********************************************************************************************************************/
-- SQL Prompt formatting off
/**********************************************************************************************************************/
SELECT
@CheckId = 1
,@Priority = 10
,@FindingGroup = 'Naming Conventions'
,@Finding = 'Using Plural in Names'
,@URLAnchor = 'naming-conventions#1';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = O.object_id
,ObjectName = O.name
,ObjectType = O.type_desc
,Details = N''Table and view names should be singular. NOTE: This could be a false-positive for names that do end with S.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.objects AS O
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON O.schema_id = S.schema_id
WHERE
O.type IN (''U'', ''V'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 1) = ''S''
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 2) <> ''SS''
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 4) NOT IN (''news'', ''plus'', ''thus'', ''goes'', ''bars'', ''axis'', ''bias'', ''iris'', ''kris'', ''nous'', ''osis'', ''itis'', ''tics'', ''opus'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 5) NOT IN (''means'', ''shoes'', ''focus'', ''basis'', ''virus'', ''bonus'', ''specs'', ''acres'', ''atlas'', ''corps'', ''lotus'', ''oasis'', ''wages'', ''twins'', ''alias'', ''minus'', ''flies'', ''genus'', ''maths'', ''locus'', ''penis'', ''nexus'', ''fries'', ''fetus'', ''sinus'', ''kudos'', ''lupus'', ''elves'', ''lexis'', ''virus'', ''ethos'', ''gauss'', ''feces'', ''mucus'', ''trics'', ''eaves'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 6) NOT IN (''status'', ''series'', ''campus'', ''comics'', ''tennis'', ''census'', ''leaves'', ''crisis'', ''basics'', ''canvas'', ''thesis'', ''radius'', ''stylus'', ''chorus'', ''genius'', ''circus'', ''corpus'', ''organs'', ''citrus'', ''debris'', ''exodus'', ''cosmos'', ''cactus'', ''nerves'', ''crises'', ''annals'', ''caucus'', ''theses'', ''fungus'', ''scrubs'', ''praxis'', ''rabies'', ''discus'', ''madras'', ''mantis'', ''hiatus'', ''cirrus'', ''shears'', ''egress'', ''pelvis'', ''cleats'', ''nimbus'', ''testis'', ''pharos'', ''plexus'', ''thymus'', ''sepsis'', ''civics'', ''haggis'', ''slacks'', ''walrus'', ''bowels'', ''adonis'', ''crocus'', ''gallus'', ''hubris'', ''litmus'', ''duress'', ''pathos'', ''chives'', ''ruckus'', ''stasis'', ''throes'', ''hooves'', ''tarsus'', ''hummus'', ''callus'', ''missus'', ''oodles'', ''animus'', ''vitals'', ''khakis'', ''soleus'', ''dermis'', ''precis'', ''thrips'', ''tallis'', ''fracas'', ''estrus'', ''reales'', ''typhus'', ''fundus'', ''clevis'', ''sulcus'', ''coleus'', ''rumpus'', ''boreas'', ''coitus'', ''chinos'', ''nomics'', ''rectus'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 7) NOT IN (''species'', ''clothes'', ''siemens'', ''glasses'', ''grounds'', ''collins'', ''genesis'', ''surplus'', ''chassis'', ''indices'', ''shelves'', ''nucleus'', ''incubus'', ''goggles'', ''innings'', ''manners'', ''thieves'', ''heavens'', ''marquis'', ''summons'', ''octopus'', ''nemesis'', ''arrears'', ''omnibus'', ''phonics'', ''stratus'', ''tropics'', ''impetus'', ''modulus'', ''bellows'', ''alumnus'', ''tetanus'', ''withers'', ''funnies'', ''trellis'', ''papyrus'', ''follies'', ''dwarves'', ''cumulus'', ''thermos'', ''cyclops'', ''forceps'', ''chamois'', ''laurels'', ''gallows'', ''greaves'', ''isthmus'', ''helices'', ''scabies'', ''ascites'', ''sheaves'', ''annulus'', ''triceps'', ''challis'', ''arbutus'', ''kinesis'', ''rickets'', ''rooibos'', ''innards'', ''humerus'', ''phallus'', ''rhombus'', ''calamus'', ''autobus'', ''varices'', ''tigress'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 8) NOT IN (''analysis'', ''diabetes'', ''emphasis'', ''overseas'', ''premises'', ''precious'', ''synopsis'', ''proceeds'', ''quarters'', ''finances'', ''asbestos'', ''potatoes'', ''syllabus'', ''calculus'', ''trousers'', ''cannabis'', ''matrices'', ''upstairs'', ''scissors'', ''stimulus'', ''vertices'', ''dialysis'', ''emeritus'', ''nautilus'', ''aerobics'', ''bacillus'', ''pancreas'', ''checkers'', ''terminus'', ''auspices'', ''shingles'', ''avionics'', ''hibiscus'', ''confines'', ''syphilis'', ''colossus'', ''buttocks'', ''knuckles'', ''sundries'', ''synopses'', ''dominoes'', ''knickers'', ''platypus'', ''platypus'', ''tinnitus'', ''clematis'', ''synapses'', ''whiskers'', ''shambles'', ''eugenics'', ''vortices'', ''exegesis'', ''ellipsis'', ''durables'', ''emphases'', ''couscous'', ''ellipses'', ''thalamus'', ''meniscus'', ''acanthus'', ''leotards'', ''entrails'', ''polemics'', ''fatigues'', ''cryonics'', ''caduceus'', ''thrombus'', ''pruritus'', ''nuptials'', ''bronchus'', ''subgenus'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 9) NOT IN (''religious'', ''amenities'', ''consensus'', ''thesaurus'', ''conscious'', ''apparatus'', ''backwards'', ''billiards'', ''psoriasis'', ''asparagus'', ''paralysis'', ''esophagus'', ''pertussis'', ''acropolis'', ''chrysalis'', ''narcissus'', ''ephemeris'', ''syntheses'', ''catharsis'', ''mnemonics'', ''verdigris'', ''sartorius'', ''ambergris'', ''nucleolus'', ''gladiolus'')
AND RIGHT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 10) NOT IN (''sunglasses'', ''binoculars'', ''gymnastics'', ''prospectus'', ''phosphorus'', ''appendices'', ''metropolis'', ''aesthetics'', ''hypotheses'', ''downstairs'', ''geophysics'', ''rendezvous'', ''mosquitoes'', ''eucalyptus'', ''hydraulics'', ''proteomics'', ''hydrolysis'', ''metastasis'', ''cretaceous'', ''spectacles'', ''metastases'', ''kinematics'', ''eurythmics'', ''portcullis'', ''rhinoceros'', ''underpants'', ''biogenesis'', ''prostheses'', ''pneumatics'', ''astragalus'', ''urinalysis'', ''ballistics'', ''chemotaxis'', ''acrobatics'', ''glycolysis'', ''strabismus'', ''hemostasis'', ''dialectics'', ''catechesis'', ''laryngitis'')
AND O.NAME NOT IN (''sysdiagrams'', ''database_firewall_rules'')
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
END;
/**********************************************************************************************************************/
SELECT
@CheckId = 29
,@Priority = 30
,@FindingGroup = 'Table Conventions'
,@Finding = 'Using Unique Constraint Instead of Unique Indexes'
,@URLAnchor = 'table-conventions#29';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = O.object_id
,ObjectName = O.name
,ObjectType = O.type_desc
,Details = N''Using Unique Constraint Instead of Unique Indexes''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.objects AS O
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON O.schema_id = S.schema_id
WHERE
O.type IN (''UQ'')
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
END;
/**********************************************************************************************************************/
SELECT
@CheckId = 14
,@Priority = 10
,@FindingGroup = 'Naming Conventions'
,@Finding = 'Column Naming'
,@URLAnchor = 'naming-conventions#14';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = C.object_id
,ObjectName = T.name + ''.'' + C.name
,ObjectType = ''COLUMN''
,Details = N''Avoid repeating the table name except where it is natural to do so.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.tables AS T
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.columns AS C ON T.object_id = C.object_id
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON T.schema_id = S.schema_id
WHERE
C.name COLLATE SQL_Latin1_General_CP1_CI_AS LIKE ''%'' + T.name COLLATE SQL_Latin1_General_CP1_CI_AS + ''%''
AND C.name NOT IN (''InvoiceDate'', ''InvoiceNumber'', ''PartNumber'', ''CustomerNumber'', ''GroupName'', ''StateCode'', ''PhoneNumber'')
AND C.name COLLATE SQL_Latin1_General_CP1_CI_AS <> T.name COLLATE SQL_Latin1_General_CP1_CI_AS + ''Id''
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = C.object_id
,ObjectName = T.name + ''.'' + C.name
,ObjectType = ''COLUMN''
,Details = N''When using generic names you should prefix the class word with a modifier like the table name if appropriate.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.tables AS T
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.columns AS C ON T.object_id = C.object_id
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON T.schema_id = S.schema_id
WHERE
C.name COLLATE SQL_Latin1_General_CP1_CI_AS IN (''name'', ''description'', ''comment'', ''code'', ''type'', ''status'', ''date'', ''time'', ''key'', ''value'', ''term'', ''class'', ''style'', ''segment'', ''default'', ''primary'', ''deleted'', ''active'', ''inactive'', ''permission'', ''locked'', ''number'', ''amount'', ''total'', ''quantity'', ''weight'', ''percent'', ''rate'', ''cost'', ''price'', ''balance'', ''average'', ''discount'', ''limit'', ''due'', ''fee'', ''fine'', ''stamp'', ''flag'', ''slug'', ''level'', ''url'', ''email'', ''address'', ''subject'', ''body'', ''alias'', ''state'', ''format'', ''group'')
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
END;
/**********************************************************************************************************************/
SELECT
@CheckId = 2
,@Priority = 10
,@FindingGroup = 'Naming Conventions'
,@Finding = 'Using Prefix in Name'
,@URLAnchor = 'naming-conventions#2';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = CASE WHEN O.type_desc COLLATE SQL_Latin1_General_CP1_CI_AS LIKE ''%constraint%'' THEN 30 ELSE ' + CAST(@Priority AS NVARCHAR(MAX)) + N' END
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = O.object_id
,ObjectName = O.name
,ObjectType = O.type_desc
,Details = N''Never use a prefix such as tbl, sp, vw in names.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.objects AS O
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON O.schema_id = S.schema_id
WHERE
O.name COLLATE SQL_Latin1_General_CP1_CI_AS NOT IN (''sp_Develop'', ''spCRUDGen'', ''sp_alterdiagram'', ''sp_creatediagram'', ''sp_dropdiagram'', ''sp_helpdiagramdefinition'', ''sp_helpdiagrams'', ''sp_renamediagram'', ''sp_upgraddiagrams'', ''fn_diagramobjects'', ''sp_WhoIsActive'', ''sp_HumanEvents'', ''sp_BlitzWho'', ''sp_BlitzCache'', ''sp_BlitzFirst'', ''sp_BlitzIndex'', ''sp_BlitzInMemoryOLTP'', ''sp_BlitzLock'', ''sp_BlitzQueryStore'', ''sp_PressureDetector'', ''sp_QuickieStore'')
AND (
LEFT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 6) IN (''covix_'', ''ncldx_'', ''clidx_'')
OR LEFT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 5) IN (''pknc_'', ''ncak_'', ''clix_'', ''_dta_'')
OR LEFT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 4) IN (''tab_'', ''pkc_'', ''idx_'', ''cak_'', ''unq_'', ''chk_'', ''ftx_'', ''gis_'', ''usp_'', ''trg_'')
OR LEFT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 3) IN (''tbl'', ''sp_'', ''xp_'', ''dt_'', ''fn_'', ''tr_'', ''usp'', ''usr'', ''uc_'', ''nk_'', ''ak_'', ''nc_'', ''ix_'', ''ux_'', ''uk_'', ''fk_'', ''uq_'', ''df_'')
OR LEFT(O.name COLLATE SQL_Latin1_General_CP1_CI_AS, 2) IN (''tb'', ''t_'', ''vw'', ''fn'', ''p_'', ''f_'')
OR O.name LIKE ''[v][A-Z]%'' COLLATE Latin1_General_BIN
OR O.name LIKE ''[t][A-Z]%'' COLLATE Latin1_General_BIN
OR O.name LIKE ''[s][p][A-Z]%'' COLLATE Latin1_General_BIN
OR O.name LIKE ''[t][r][A-Z]%'' COLLATE Latin1_General_BIN
)
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
/* Find Table Columns */
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = C.object_id
,ObjectName = T.name + ''.'' + C.name
,ObjectType = ''COLUMN''
,Details = N''Never use a prefix such as fld, col, u_, c_, ... in column names.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.columns AS C
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.tables AS T ON C.object_id = T.object_id
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON T.schema_id = S.schema_id
WHERE
LEFT(C.name COLLATE SQL_Latin1_General_CP1_CI_AS, 4) IN (''fld_'', ''col_'')
OR LEFT(C.name COLLATE SQL_Latin1_General_CP1_CI_AS, 2) IN (''u_'', ''c_'')
OR C.name LIKE ''[f][A-Z]%'' COLLATE Latin1_General_BIN
OR C.name LIKE ''[c][A-Z]%'' COLLATE Latin1_General_BIN
OR C.name LIKE ''[u][A-Z]%'' COLLATE Latin1_General_BIN
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
/* Find User-Defined Data Types */
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = T.user_type_id
,ObjectName = T.name
,ObjectType = ''USER-DEFINED DATA TYPE''
,Details = N''Never use a prefix such as ud_, ud, ... in user-defined data type names.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.types AS T
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON T.schema_id = S.schema_id
WHERE
T.is_user_defined = 1
AND (
LEFT(T.name COLLATE SQL_Latin1_General_CP1_CI_AS, 3) IN (''ud_'')
OR T.name LIKE ''[u][d][A-Z]%'' COLLATE Latin1_General_BIN
)
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
END;
/**********************************************************************************************************************/
SELECT
@CheckId = 5
,@Priority = 5
,@FindingGroup = 'Naming Conventions'
,@Finding = 'Including Special Characters in Name'
,@URLAnchor = 'naming-conventions#5';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = O.object_id
,ObjectName = O.name
,ObjectType = O.type_desc
,Details = N''Special characters should not be used in names.''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.objects AS O
INNER JOIN ' + QUOTENAME(@DatabaseName) + N'.sys.schemas AS S ON O.schema_id = S.schema_id
WHERE
O.type_desc NOT IN (''DEFAULT_CONSTRAINT'', ''FOREIGN_KEY_CONSTRAINT'', ''PRIMARY_KEY_CONSTRAINT'', ''INTERNAL_TABLE'', ''CHECK_CONSTRAINT'', ''UNIQUE_CONSTRAINT'', ''SQL_INLINE_TABLE_VALUED_FUNCTION'', ''TYPE_TABLE'', ''SEQUENCE_OBJECT'')
AND O.name NOT IN (''__RefactorLog'', ''__MigrationLog'', ''__MigrationLogCurrent'', ''__SchemaSnapshot'', ''__SchemaSnapshotDateDefault'', ''fn_diagramobjects'', ''sp_alterdiagram'', ''sp_creatediagram'', ''sp_dropdiagram'', ''sp_helpdiagramdefinition'', ''sp_helpdiagrams'', ''sp_renamediagram'', ''sp_upgraddiagrams'', ''database_firewall_rules'', ''sp_Develop'', ''sp_WhoIsActive'', ''__EFMigrationsHistory'')
AND (
O.name LIKE ''%[^A-Z0-9@$#]%'' COLLATE Latin1_General_CI_AI /* contains illegal characters */
OR O.name NOT LIKE ''[A-Z]%'' COLLATE Latin1_General_CI_AI /* doesn''t start with a character */
)
OPTION (RECOMPILE);';
EXEC sys.sp_executesql @stmt = @StringToExecute;
IF @Debug = 2 AND @StringToExecute IS NOT NULL PRINT @StringToExecute;
END;
/**********************************************************************************************************************/
SELECT
@CheckId = 13
,@Priority = 50
,@FindingGroup = 'Naming Conventions'
,@Finding = 'Concatenating Two Table Names'
,@URLAnchor = 'naming-conventions#13';
/**********************************************************************************************************************/
IF NOT EXISTS (SELECT 1 FROM #SkipCheck AS SC WHERE SC.CheckId = @CheckId AND SC.ObjectName IS NULL)
BEGIN
IF @Debug IN (1, 2) RAISERROR(N'Running CheckId [%d]', 0, 1, @CheckId) WITH NOWAIT;
SET @StringToExecute = N'
INSERT INTO
#Finding (CheckId, Database_Id, DatabaseName, FindingGroup, Finding, URL, Priority, Schema_Id, SchemaName, Object_Id, ObjectName, ObjectType, Details)
SELECT
CheckId = ' + CAST(@CheckId AS NVARCHAR(MAX)) + N'
,Database_Id = ' + CAST(@DatabaseId AS NVARCHAR(MAX)) + N'
,DatabaseName = ''' + CAST(@DatabaseName AS NVARCHAR(MAX)) + N'''
,FindingGroup = ''' + CAST(@FindingGroup AS NVARCHAR(MAX)) + N'''
,Finding = ''' + CAST(@Finding AS NVARCHAR(MAX)) + N'''
,URL = ''' + CAST(@URLBase + @URLAnchor AS NVARCHAR(MAX)) + N'''
,Priority = ' + CAST(@Priority AS NVARCHAR(MAX)) + N'
,Schema_Id = S.schema_id
,SchemaName = S.name
,Object_Id = T.object_id
,ObjectName = T.name
,ObjectType = T.type_desc
,Details = N''Avoid, where possible, concatenating two table names together. Use "Subscription" instead of "NewspaperReader".''
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.tables AS T
INNER JOIN (
SELECT
DoubleName = T1.name + T2.name
FROM
' + QUOTENAME(@DatabaseName) + N'.sys.tables AS T1