-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbo.sp_GetDependencies.sql
2262 lines (2011 loc) · 96.6 KB
/
dbo.sp_GetDependencies.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
SET QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_GetDependencies] @inputs xml
as
/*==============================================================================
Input Format
<Tables>
<Table Name="a" Owner="b"/>
<Table Name="c" Owner="d"/>
</Tables>
How to write a reliable dependency checker (for SQL Server 2K5):
The following code accepts a collection of database objects (tables,
views, stored procedures, and functions) and can operate in one of five modes:
* Mode I (fastest): Given the collection, the script returns dependency and deployment
order for all objects in the collection. To activate this mode, first
populate #tblRequestedObjects and then set the following config values:
@IncludeAllDBObjects = 0
@IncludeDependencies = 0
@IncludeDependants = 0
* Mode II: Given the collection, the script returns all objects on which
the ones in the collection depend on, together with the dependency and
deployment order. This is done in a recursive manner to return all dependencies.
To activate this mode, first populate #tblRequestedObjects and then set
the following config values:
@IncludeAllDBObjects = 0
@IncludeDependencies = 1
@IncludeDependants = 0
* Mode III: Given the collection, the script returns all objects that depend
on the ones provided in the collection, together with the dependency and
deployment order. This is also done recursively to return all dependencies.
To activate this mode, first populate #tblRequestedObjects and then set
the following config values:
@IncludeAllDBObjects = 0
@IncludeDependencies = 0
@IncludeDependants = 1
* Mode VI: This is combination of Mode II and III. Given the collection,
the script returns all objects that depend on the ones provided in the collection,
as well as all objects on which the ones in the collection depend on.
The dependency and deployment order are returned as well. To activate this mode,
first populate #tblRequestedObjects and then set the following config values:
@IncludeAllDBObjects = 0
@IncludeDependencies = 1
@IncludeDependants = 1
* Mode V (slowest): The script returns the dependency and deployment order
of all standard objects (i.e., tables, views, procs, functions) in the database.
To activate this mode, first populate #tblRequestedObjects and then set
the following config values:
@IncludeAllDBObjects = 1
@IncludeDependencies = 0 (this parameter is NA in this case)
@IncludeDependants = 0 (this parameter is NA in this case)
The script operates as follows:
1. Collect information about all standard objects in the database (tables,
views, procs, functions) and store it in #tblAllDBRoutinesTablesViews.
2. Before finding dependencies, if @ValidateViews then all views are checked
to ensure that there are no binding issues.
3. Table #MySysdepends is created - this table will contain all dependencies
between standard database objects (even those omitted from sysdepends).
The table is initially populated with table dependencies based on FK
information, direct-dependency information from sysdepends/sql_dependencies,
and child-object dependencies from sysdepends/sql_dependencies as well.
4. Table #tblTextBasedObjects is created - this table holds the text
of all text-based objects in the database (views, functions, procs, triggers).
5. All comments are strippted out from the CREATE statement of objects in
#tblTextBasedObjects in order to search for dependencies within the text.
6. Based on the operation mode, we search for dependencies within
the comment-free text (we consider both direct dependencies as well
as dependencies via child-objects denoted as indirect-dependecies).
7. After all dependencies were found we iterate to find the dependency
level and deployment order of all relevant objects.
Some terms and definitions:
DependencyLevel - if an object depends on another, and the latter depends
on yet another object, then when all three are plotted by the algorithm
they will have DependencyLevel 0, 1, and 2, respectively.
DeploymentOrder - this is the order in which objects should be deployed
in order to ensure that all dependants are created first.
Note: In SQL2K5 the script also takes into consideration the use of
synonyms when searching the text-body of DB objects to detect dependencies.
==============================================================================*/
SET NOCOUNT ON
-- User will populate this table with owner/schema and object names
-- or set @IncludeAllDBObjects BIT to 1.
IF OBJECT_ID('tempdb..#tblRequestedObjects') IS NOT NULL
DROP TABLE #tblRequestedObjects
CREATE TABLE #tblRequestedObjects (
ObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default,
ObjectName NVARCHAR(128) COLLATE database_default)
INSERT INTO #tblRequestedObjects
SELECT Distinct
Colname.value('@Owner','nvarchar(128)'),
ColName.value('@Name','nVarchar(128)')
FROM @inputs.nodes('Tables/Table') MyAlias(ColName)
-- User: Populate #tblRequestedObjects here.
--INSERT INTO #tblRequestedObjects values('Sg', 'vwPolicy')
--INSERT INTO #tblRequestedObjects values('Sg', 'vwPolicy3')
--INSERT INTO #tblRequestedObjects values('wfe', 'vwJobVersion')
--INSERT INTO #tblRequestedObjects values('inv', 'vwPart')
--INSERT INTO #tblRequestedObjects values('dbo', 'DimProduct')
--INSERT INTO #tblRequestedObjects values('dbo', 'vDMPrep')
--INSERT INTO #tblRequestedObjects values('dbo', 'ISOweek')
-- The user should insert records to #tblRequestedObjects here. For example:
-- INSERT INTO #tblRequestedObjects VALUES('dbo', 'utbMyTable')
-- INSERT INTO #tblRequestedObjects SELECT USER_NAME(uid), name FROM sysobjects WHERE ...
-- Example using AdventureWorks objects:
-- INSERT INTO #tblRequestedObjects values('dbo', 'DimCustomer')
-- INSERT INTO #tblRequestedObjects values('dbo', 'DimProduct')
-- INSERT INTO #tblRequestedObjects values('dbo', 'vDMPrep')
-- INSERT INTO #tblRequestedObjects values('dbo', 'ISOweek')
DECLARE @IncludeAllDBObjects BIT
DECLARE @IncludeDependencies BIT -- objects on which a current object depends on that are not in #tblRequestedObjects
DECLARE @IncludeDependants BIT -- objects that depend on a current object that are not in #tblRequestedObjects
DECLARE @IncludeReplicationObjects BIT -- set this bit to 0 to not consider replication objects
DECLARE @ReturnFoundDependencies BIT
DECLARE @ReturnDeploymentOrder BIT
DECLARE @IncludeWarningForCircularDependencies BIT
DECLARE @ValidateViews BIT
-- User configuration- set the mode of operation of the algorithm:
-- 1) @IncludeAllDBObjects - set this pamameter to 1 if you wish to find dependencies between all
-- database objects and not only the ones specified earlier in #tblRequestedObjects
-- 2) @IncludeWarningForCircularDependencies - set this parameter to 1 to return a result set
-- with all circular dependencies
-- 3) @IncludeDependencies - set to 1 to find all objects on which the objects in #tblRequestedObjects depend on.
-- 4) @IncludeDependants - set to 1 to find all objects that depend on the objects in #tblRequestedObjects.
-- 5) @IncludeReplicationObjects - set to 1 to include replicatin objects (not recommended).
-- 6) @ReturnFoundDependencies - return a result set with all found dependencies.
-- 7) @IncludeWarningForCircularDependencies - return a result set with all circular dependencies found.
-- 8) @ValidateViews - check that the schema of all views are bound correctly (no missing underlying objects).
SET @IncludeAllDBObjects = 0
SET @IncludeDependencies = 1
SET @IncludeDependants = 0
SET @IncludeReplicationObjects = 0
SET @ReturnFoundDependencies = 1
SET @ReturnDeploymentOrder = 0
SET @IncludeWarningForCircularDependencies = 0
SET @ValidateViews = 1
-- Put square brackets where needed.
UPDATE #tblRequestedObjects
SET ObjectOwnerOrSchema = CASE
WHEN LEFT(ObjectOwnerOrSchema, 1) <> N'[' AND RIGHT(ObjectOwnerOrSchema, 1) <> N']'
THEN N'[' + ObjectOwnerOrSchema + N']'
WHEN LEFT(ObjectOwnerOrSchema, 1) <> N'[' AND RIGHT(ObjectOwnerOrSchema, 1) = N']'
THEN N'[' + ObjectOwnerOrSchema
WHEN LEFT(ObjectOwnerOrSchema, 1) = N'[' AND RIGHT(ObjectOwnerOrSchema, 1) <> N']'
THEN ObjectOwnerOrSchema + N']'
END,
ObjectName = CASE
WHEN LEFT(ObjectName, 1) <> N'[' AND RIGHT(ObjectName, 1) <> N']'
THEN N'[' + ObjectName + N']'
WHEN LEFT(ObjectName, 1) <> N'[' AND RIGHT(ObjectName, 1) = N']'
THEN N'[' + ObjectName
WHEN LEFT(ObjectName, 1) = N'[' AND RIGHT(ObjectName, 1) <> N']'
THEN ObjectName + N']'
END
-- Make sure that all objects provided by the user exist in the database. If not- abort.
Delete from #tblRequestedObjects
where OBJECT_ID(ObjectOwnerOrSchema + '.' + ObjectName) IS NULL
if EXISTS(SELECT * FROM #tblRequestedObjects WHERE OBJECT_ID(ObjectOwnerOrSchema + '.' + ObjectName) IS NULL)
AND (@IncludeAllDBObjects = 0 OR @IncludeAllDBObjects IS NULL)
BEGIN
RAISERROR('Some of the objects provided in #tblRequestedObjects do not exist in the database. Aborting.', 16, 1)
RETURN
END
-- #tblAllDBRoutinesTablesViews contains information about all
-- procedures, functions, tables, and views in the database
-- and is used for different purposes throughout the script.
IF OBJECT_ID('tempdb..#tblAllDBRoutinesTablesViews') IS NOT NULL
DROP TABLE #tblAllDBRoutinesTablesViews
CREATE TABLE #tblAllDBRoutinesTablesViews (
ObjectID INT NOT NULL PRIMARY KEY CLUSTERED,
ObjectType NVARCHAR(32) COLLATE database_default NOT NULL,
ObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default NOT NULL,
ObjectName NVARCHAR(128) COLLATE database_default NOT NULL,
-- ObjectNameForLikeSearches1, 2, 3, 4 - contains a string for text searches using the LIKE clause
ObjectNameForLikeSearches1 NVARCHAR(200) COLLATE database_default,
ObjectNameForLikeSearches2 NVARCHAR(200) COLLATE database_default,
ObjectNameForLikeSearches3 NVARCHAR(200) COLLATE database_default,
ObjectNameForLikeSearches4 NVARCHAR(200) COLLATE database_default)
-- We populate the table #tblAllDBRoutinesTablesViews regardless of the user input.
-- Stored procedures and functions.
INSERT INTO #tblAllDBRoutinesTablesViews (ObjectID, ObjectOwnerOrSchema, ObjectName, ObjectType)
SELECT OBJECT_ID('[' + ROUTINE_SCHEMA + '].[' + ROUTINE_NAME + ']'),
ROUTINE_SCHEMA,
ROUTINE_NAME,
CASE
WHEN ROUTINE_TYPE = N'PROCEDURE' THEN N'PROCEDURE'
WHEN ROUTINE_TYPE = N'FUNCTION' THEN N'FUNCTION'
END
FROM INFORMATION_SCHEMA.ROUTINES
WHERE OBJECTPROPERTY(OBJECT_ID('[' + ROUTINE_SCHEMA + '].[' + ROUTINE_NAME + ']'), 'IsMSShipped') = 0
-- Tables and views.
INSERT INTO #tblAllDBRoutinesTablesViews (ObjectID, ObjectOwnerOrSchema, ObjectName, ObjectType)
SELECT OBJECT_ID('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'),
TABLE_SCHEMA,
TABLE_NAME,
CASE
WHEN TABLE_TYPE = N'VIEW' THEN N'VIEW'
WHEN TABLE_TYPE = N'BASE TABLE' THEN N'TABLE'
END
FROM INFORMATION_SCHEMA.TABLES
WHERE OBJECTPROPERTY(OBJECT_ID('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), 'IsMSShipped') = 0
-- View validation:
-- If @ValidateViews = 1 then we check if the view has any binding issues
-- (e.g., to make sure that objects references in the views exist in the database).
-- If any errors occur during the view validation, the entire script will stop
-- and inform the user of issues with the problematic view.
DECLARE @sSPID NVARCHAR(128)
DECLARE @CurrObjectID INT
DECLARE @CurrObjectName NVARCHAR(128)
DECLARE @CurrObjectType NVARCHAR(128)
DECLARE @CurrObjectOwnerOrSchema NVARCHAR(128)
SELECT @CurrObjectID = MIN(ObjectID)
FROM #tblAllDBRoutinesTablesViews
WHERE ObjectType = 'VIEW'
IF @ValidateViews = 1
BEGIN
WHILE @CurrObjectID IS NOT NULL
BEGIN
SELECT @CurrObjectOwnerOrSchema = REPLACE(ObjectOwnerOrSchema, '''', ''''''),
@CurrObjectName = REPLACE(ObjectName, '''', '''''')
FROM #tblAllDBRoutinesTablesViews
WHERE ObjectID = @CurrObjectID
EXEC('IF EXISTS(SELECT TOP 1 * FROM [' + @CurrObjectOwnerOrSchema + '].[' + @CurrObjectName + ']) print(''View [' + @CurrObjectOwnerOrSchema + '].[' + @CurrObjectName + '] validated'')')
IF @@ERROR <> 0
BEGIN
RAISERROR('View [%s].[%s] references objects that are not available in the underlying database.', 16, 1, @CurrObjectOwnerOrSchema, @CurrObjectName)
RETURN
END
SELECT @CurrObjectID = MIN(ObjectID)
FROM #tblAllDBRoutinesTablesViews
WHERE ObjectID > @CurrObjectID
AND ObjectType = 'VIEW'
END
END
-- #tblObjects includes all objects that need to be considered for dependency tracking:
-- Initially the table contains all the objects that are requested by the user
-- (i.e., if @IncludeAllDBObjects = 1 then #tblObjects contains all DB objects; otherwise
-- it will only include objects in #tblRequestedObjects).
-- Later, the table will include the dependencies and dependants, as requested by the user.
-- NOTE: ENTRIES IN #tblObjects DO NOT CONTAIN THE DEPENDENCY OR DEPLOYMENT ORDER !!!
IF OBJECT_ID('tempdb..#tblObjects') IS NOT NULL
DROP TABLE #tblObjects
CREATE TABLE #tblObjects (
ObjectID INT NOT NULL PRIMARY KEY CLUSTERED,
ObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default NOT NULL,
ObjectName NVARCHAR(128) COLLATE database_default NOT NULL,
ObjectType NVARCHAR(128) COLLATE database_default NOT NULL,
-- AuxiliaryOrdering is used for deployment order and accepts the following values:
-- 1 for tables, 2 views, 3 functions, 4 procs.
AuxiliaryOrdering INT NOT NULL,
-- ObjectNameForLikeSearches1, 2, 3, 4 - contains a string for text searches using the LIKE clause
ObjectNameForLikeSearches1 NVARCHAR(128) COLLATE database_default,
ObjectNameForLikeSearches2 NVARCHAR(128) COLLATE database_default,
ObjectNameForLikeSearches3 NVARCHAR(128) COLLATE database_default,
ObjectNameForLikeSearches4 NVARCHAR(128) COLLATE database_default)
-- #tblObjects contains the objects that have to be considered for dependency checks.
-- If @IncludeAllDBObjects = 1 then #tblObjects contains all database objects;
-- otherwise #tblObjects only contains the objects requested in #tblRequestedObjects.
IF @IncludeAllDBObjects = 1
BEGIN
-- In this case, #tblObjects includes all DB objects
INSERT INTO #tblObjects (ObjectID, ObjectOwnerOrSchema, ObjectName, ObjectType, AuxiliaryOrdering)
SELECT ObjectID, ObjectOwnerOrSchema, ObjectName, ObjectType,
CASE WHEN ObjectType = 'TABLE' THEN 1
WHEN ObjectType = 'VIEW' THEN 2
WHEN ObjectType = 'PROCEDURE' THEN 3
WHEN ObjectType = 'FUNCTION' THEN 4
END
FROM #tblAllDBRoutinesTablesViews
END
ELSE
BEGIN
-- Here, #tblObjects only includes the requested objects
INSERT INTO #tblObjects (ObjectID, ObjectOwnerOrSchema, ObjectName, ObjectType, AuxiliaryOrdering)
SELECT a.ObjectID, a.ObjectOwnerOrSchema, a.ObjectName, a.ObjectType,
CASE WHEN ObjectType = 'TABLE' THEN 1
WHEN ObjectType = 'VIEW' THEN 2
WHEN ObjectType = 'PROCEDURE' THEN 3
WHEN ObjectType = 'FUNCTION' THEN 4
END
FROM #tblAllDBRoutinesTablesViews a
INNER JOIN #tblRequestedObjects z
ON '[' + a.ObjectOwnerOrSchema + ']' = z.ObjectOwnerOrSchema
AND '[' + a.ObjectName + ']' = z.ObjectName
END
-- sys.sql_dependencies does not include information about tables and FK dependencies, and does not
-- track dependencies between objects caused by child-object dependencies.
-- #MySysdepends is our interpretation of database object dependencies, and initially includes:
-- All dependency information from sys.sql_dependencies.
-- Table dependencies caused by FK constraints (which is not in sys.sql_dependencies)
-- Dependencies caused by child-objects.
--
-- Note!: #MySysdepends contains dependency information for all relevant objects in #tblObjects.
--===================================================================
-- Step 1 Start
--===================================================================
DECLARE @Cnt INT
DECLARE @Cnt1 INT
DECLARE @Cnt2 INT
DECLARE @tmpSQLStr VARCHAR(8000)
DECLARE @StopLoop BIT
SET @sSPID = CAST(@@SPID AS VARCHAR(32))
IF OBJECT_ID('tempdb..#MySysdepends') IS NOT NULL
DROP TABLE #MySysdepends
CREATE TABLE #MySysdepends (
id INT NOT NULL,
depid INT NOT NULL,
-- depType holds the type of dependency:
-- 'D' - direct dependency between 2 objects, as found in sys.sql_dependencies
-- 'C' - dependency via child object, as found from sys.sql_dependencies
-- 'S' - direct dependency as found in the text-based dependency checks
-- 'T' - dependency via child objects as concluded from the text-based dependency check.
depType CHAR(1) COLLATE database_default NOT NULL,
idObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default NOT NULL,
idObjectName NVARCHAR(128) COLLATE database_default NOT NULL,
idObjectType NVARCHAR(128) COLLATE database_default NOT NULL,
idObjectNameForLikeSearches1 NVARCHAR(200) COLLATE database_default,
idObjectNameForLikeSearches2 NVARCHAR(200) COLLATE database_default,
idObjectNameForLikeSearches3 NVARCHAR(200) COLLATE database_default,
idObjectNameForLikeSearches4 NVARCHAR(200) COLLATE database_default,
depidObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default NOT NULL,
depidObjectName NVARCHAR(128) COLLATE database_default NOT NULL,
depidObjectType NVARCHAR(128) COLLATE database_default NOT NULL,
depidObjectNameForLikeSearches1 NVARCHAR(200) COLLATE database_default,
depidObjectNameForLikeSearches2 NVARCHAR(200) COLLATE database_default,
depidObjectNameForLikeSearches3 NVARCHAR(200) COLLATE database_default,
depidObjectNameForLikeSearches4 NVARCHAR(200) COLLATE database_default,
-- AuxiliaryInt is used for internal purposes.
AuxiliaryInt INT)
EXEC('CREATE UNIQUE CLUSTERED INDEX CI_MySysdepends1' + @sSPID + ' ON #MySysdepends(id, depid)')
EXEC('CREATE UNIQUE NONCLUSTERED INDEX CI_MySysdepends2' + @sSPID + ' ON #MySysdepends(depid, id)')
-- Capture all initial dependencies:
-- 1. Table FK dependency (including self-dependency):
-- 1.1. Get all foreign tables that references tables in #tblObjects.
-- 1.2. Get all primary tables with foreign tables in #tblObjects.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT OBJECT_ID('[' + a.TABLE_SCHEMA + '].[' + a.TABLE_NAME + ']'),
OBJECT_ID('[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']'),
a.TABLE_SCHEMA,
a.TABLE_NAME,
'TABLE',
c.TABLE_SCHEMA,
c.TABLE_NAME,
'TABLE',
'D',
2
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS a
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS b
ON a.CONSTRAINT_SCHEMA = b.CONSTRAINT_SCHEMA
AND a.CONSTRAINT_NAME = b.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
ON b.UNIQUE_CONSTRAINT_SCHEMA = c.CONSTRAINT_SCHEMA
AND b.UNIQUE_CONSTRAINT_NAME = c.CONSTRAINT_NAME
-- Only get objects of interest
INNER JOIN #tblObjects d
ON (OBJECT_ID('[' + a.TABLE_SCHEMA + '].[' + a.TABLE_NAME + ']') = d.ObjectID
OR OBJECT_ID('[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']') = d.ObjectID)
-- 2) Get all dependencies from sys.sql_dependencies (only ones that were not yet recorded),
-- that relate in some way to objects in #tblObjects:
-- 2.1. Get all first-level dependencies (objects on which the items in #tblObjects depend on)
-- Dependency on tables, views, procs, functions.
-- First level/hierarchy
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
c.ObjectID,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
c.ObjectOwnerOrSchema,
c.ObjectName,
c.ObjectType,
'D', -- direct dependency
2
FROM #tblObjects a
INNER JOIN sys.sql_dependencies b
ON a.ObjectID = b.[object_id]
INNER JOIN #tblAllDBRoutinesTablesViews c
ON b.[referenced_major_id] = c.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND c.ObjectID = x.depid
WHERE x.id IS NULL
-- 2.2. Include child-parent object dependencies:
-- Children of objects in #tblObjects that depend on other objects.
-- Note: We do not need to consider the case where objects in #tblObjects
-- depend on children of other objects, since that is never possible.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
d.ObjectID,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
d.ObjectOwnerOrSchema,
d.ObjectName,
d.ObjectType,
'C', -- dependency via child-object
2
FROM #tblObjects a
INNER JOIN sysobjects b
ON a.ObjectID = b.parent_obj
INNER JOIN sys.sql_dependencies c
ON b.id = c.[object_id]
INNER JOIN #tblAllDBRoutinesTablesViews d
ON c.[referenced_major_id] = d.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND d.ObjectID = x.depid
WHERE x.id IS NULL
-- 3) Hierarchical dependencies: We found objects on which items in #tblObjects
-- depend on (call these objects Set #1). We now need to find the objects
-- on which items in Set #1 depend on, recursively.
-- Initial values to jump-start the loop below.
SET @Cnt1 = 1
SET @Cnt2 = 1
WHILE @Cnt1 > 0 OR @Cnt2 > 0
BEGIN
UPDATE #MySysdepends
SET AuxiliaryInt = AuxiliaryInt - 1
-- Consider hierarchical dependencies
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.depid,
c.ObjectID,
a.depidObjectOwnerOrSchema,
a.depidObjectName,
a.depidObjectType,
c.ObjectOwnerOrSchema,
c.ObjectName,
c.ObjectType,
'D',
2
FROM #MySysdepends a
INNER JOIN sys.sql_dependencies b
ON a.depid = b.[object_id]
INNER JOIN #tblAllDBRoutinesTablesViews c
ON b.[referenced_major_id] = c.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.depid = x.id
AND c.ObjectID = x.depid
WHERE a.AuxiliaryInt = 1
AND x.id IS NULL
SET @Cnt1 = @@ROWCOUNT
-- Include child-parent object dependencies:
-- Children of objects in #tblObjects depend on other objects.
-- Note: We do not need to consider the case where objects in #tblObjects
-- depend on children of other objects, since that is never possible.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.depid,
d.ObjectID,
a.depidObjectOwnerOrSchema,
a.depidObjectName,
a.depidObjectType,
d.ObjectOwnerOrSchema,
d.ObjectName,
d.ObjectType,
'C',
2
FROM #MySysdepends a
INNER JOIN sysobjects b
ON a.depid = b.parent_obj
INNER JOIN sys.sql_dependencies c
ON b.id = c.[object_id]
INNER JOIN #tblAllDBRoutinesTablesViews d
ON c.[referenced_major_id] = d.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.depid = x.id
AND d.ObjectID = x.depid
WHERE a.AuxiliaryInt = 1
AND x.id IS NULL
SET @Cnt2 = @@ROWCOUNT
END -- WHILE
-- At this point there is no need to update AuxiliaryInt
-- since all objects already have AuxiliaryInt = 1.
-- 4) Get all dependants - here we look at first level of dependants
-- (i.e., objects that depend on items in #tblObjects).
-- Dependants of the type table, view, proc, function.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
c.ObjectID,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
c.ObjectOwnerOrSchema,
c.ObjectName,
c.ObjectType,
'D',
2
FROM #tblAllDBRoutinesTablesViews a
INNER JOIN sys.sql_dependencies b
ON b.[object_id] = a.ObjectID
INNER JOIN #tblObjects c
ON b.[referenced_major_id] = c.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND c.ObjectID = x.depid
WHERE x.id IS NULL
-- 5) Include child-parent object relationships.
-- Children of objects that are not in #tblObjects depend on objects in #tblObjects.
-- Note: We do not need to consider the case where objects that are not in #tblObjects
-- depend on children of objects in #tblObjects, since that is never possible.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
d.ObjectID,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
d.ObjectOwnerOrSchema,
d.ObjectName,
d.ObjectType,
'C',
2
FROM #tblAllDBRoutinesTablesViews a
INNER JOIN sysobjects b
ON a.ObjectID = b.parent_obj
INNER JOIN sys.sql_dependencies c
ON b.id = c.[object_id]
INNER JOIN #tblObjects d
ON c.[referenced_major_id] = d.ObjectID
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND d.ObjectID = x.depid
WHERE x.id IS NULL
-- 6) Hierarchical dependants: We found objects that depend on items in #tblObjects
-- (denote those objects as Set #2). We now look for other objects that depend on the
-- objects in Set #2, recursively.
-- Update AuxiliaryInt before entering the loop.
UPDATE a
SET a.AuxiliaryInt = 2
FROM #MySysdepends a
INNER JOIN #tblObjects b
ON a.id = b.ObjectID
-- Jump-start the loop.
SET @Cnt1 = 1
SET @Cnt2 = 1
WHILE @Cnt1 > 0 OR @Cnt2 > 0
BEGIN
UPDATE #MySysdepends
SET AuxiliaryInt = AuxiliaryInt - 1
-- Dependants of the type table, view, proc, function.
-- Consider hierarchical dependencies.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
c.id,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
c.idObjectOwnerOrSchema,
c.idObjectName,
c.idObjectType,
'D',
2
FROM #tblAllDBRoutinesTablesViews a
INNER JOIN sys.sql_dependencies b
ON b.[object_id] = a.ObjectID
INNER JOIN #MySysdepends c
ON b.[referenced_major_id] = c.id
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND c.id = x.depid
WHERE c.AuxiliaryInt = 1
AND x.id IS NULL
SET @Cnt1 = @@ROWCOUNT
-- Include child-parent object dependencies.
-- Children of objects that are not in #tblObjects depend on objects in #tblObjects.
-- Note: We do not need to consider the case where objects that are not in #tblObjects
-- depend on children of objects in #tblObjects, since that is never possible.
INSERT INTO #MySysdepends (
id,
depid,
idObjectOwnerOrSchema,
idObjectName,
idObjectType,
depidObjectOwnerOrSchema,
depidObjectName,
depidObjectType,
depType,
AuxiliaryInt)
SELECT DISTINCT a.ObjectID,
d.id,
a.ObjectOwnerOrSchema,
a.ObjectName,
a.ObjectType,
d.idObjectOwnerOrSchema,
d.idObjectName,
d.idObjectType,
'C',
2
FROM #tblAllDBRoutinesTablesViews a
INNER JOIN sysobjects b
ON a.ObjectID = b.parent_obj
INNER JOIN sys.sql_dependencies c
ON b.id = c.[object_id]
INNER JOIN #MySysdepends d
ON c.[referenced_major_id] = d.id
LEFT OUTER JOIN #MySysdepends x
ON a.ObjectID = x.id
AND d.id = x.depid
WHERE d.AuxiliaryInt = 1
AND x.id IS NULL
SET @Cnt2 = @@ROWCOUNT
END -- WHILE
--===================================================================
-- Step 1 Completed
--===================================================================
-- At this point we have obtained all information from sysdepends, as well as FK relationships.
-- We now continue with text-based dependency checks.
DECLARE @CurrIdx INT
DECLARE @CurrOffset INT
DECLARE @CurrColid INT
DECLARE @CurrColText NVARCHAR(4000)
DECLARE @CurrTxtPtr BINARY(16)
DECLARE @i INT
DECLARE @CurrDataLength INT
DECLARE @CommentCounter INT
DECLARE @InComment BIT
DECLARE @tmpString NVARCHAR(280)
DECLARE @Diff INT
DECLARE @StartStr NVARCHAR(32)
DECLARE @EndStr NVARCHAR(32)
DECLARE @dbgDateTime1 DATETIME
DECLARE @dbgDateTime2 DATETIME
-- #tblTextBasedObjects holds all text-based objects of interest and their body text.
IF OBJECT_ID('tempdb..#tblTextBasedObjects') IS NOT NULL
DROP TABLE #tblTextBasedObjects
CREATE TABLE #tblTextBasedObjects (
ObjectID INT NOT NULL PRIMARY KEY NONCLUSTERED,
ObjectType NVARCHAR(32) COLLATE database_default NOT NULL,
ObjectOwnerOrSchema NVARCHAR(128) COLLATE database_default NOT NULL,
ObjectName NVARCHAR(128) COLLATE database_default NOT NULL,
-- ObjectText contains the CREATE statement for each text-based object.
ObjectText NVARCHAR(MAX) COLLATE database_default,
-- ObjectTextWithoutComments stored the CREATE statement for each object without code comments.
ObjectTextWithoutComments NVARCHAR(MAX) COLLATE database_default)
-- We use @sSPID in the index name to avoid the case where several users
-- are running the same script on the same database and cause index name conflicts.
SET @sSPID = CAST(@@SPID AS VARCHAR(32))
EXEC('CREATE UNIQUE CLUSTERED INDEX CI_tblTextBasedObjects' + @sSPID + ' ON #tblTextBasedObjects(ObjectID, ObjectType) ')
--====================================================================
-- Step 2 Starts
--====================================================================
-- On top of the dependency found so far, we also parse the text of all
-- stored procs, functions, views, and triggers. We parse out all the comments
-- in their code, and then look for references to other objects.
IF @IncludeDependencies = 1
OR @IncludeDependants = 1
OR @IncludeAllDBObjects = 1
BEGIN
-- Views, procs, and functions.
INSERT INTO #tblTextBasedObjects (
ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType)
SELECT ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType
FROM #tblAllDBRoutinesTablesViews
WHERE ObjectType IN ('VIEW', 'PROCEDURE', 'FUNCTION')
AND OBJECTPROPERTY(ObjectID, 'IsMSShipped') = 0
-- Triggers
INSERT INTO #tblTextBasedObjects (
ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType)
SELECT id,
USER_NAME(uid),
name,
N'TRIGGER'
FROM sysobjects a
INNER JOIN #tblAllDBRoutinesTablesViews b
ON a.parent_obj = b.ObjectID
WHERE a.xtype = 'TR'
AND OBJECTPROPERTY(a.id, 'IsMSShipped') = 0
END
ELSE -- only consider objects in #tblObjects or triggers with parent objects in #tblObjects
BEGIN
-- Text-based objects from #tblObjects
INSERT INTO #tblTextBasedObjects (
ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType)
SELECT ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType
FROM #tblObjects
WHERE ObjectType IN ('VIEW', 'PROCEDURE', 'FUNCTION')
-- Triggers that their parent objects (tables, views) are in #tblObjects.
INSERT INTO #tblTextBasedObjects (
ObjectID,
ObjectOwnerOrSchema,
ObjectName,
ObjectType)
SELECT a.id,
USER_NAME(a.uid),
a.name,
'TRIGGER'
FROM sysobjects a
INNER JOIN #tblObjects b
ON a.parent_obj = b.ObjectID
WHERE a.xtype = 'TR'
AND OBJECTPROPERTY(a.id, 'IsMSShipped') = 0
END
/* debug */
-- SET @dbgDateTime1 = getdate()
-- Get the text of all text-based objects from sys.sql_modules.
UPDATE a
SET a.ObjectText = b.[definition]
FROM #tblTextBasedObjects a
INNER JOIN sys.sql_modules b
ON a.ObjectID = b.[object_id]
-- Do not consider encrypted objects
-- Here we use syscomments since it has the encryption info, which is
-- not available in sys.sql_modules.
DELETE a
FROM #tblTextBasedObjects a
INNER JOIN syscomments b
ON a.ObjectID = b.id
WHERE b.encrypted = 1
-- The column ObjectTextWithoutComments will contain the parsed CREATE statement of each object,
-- (i.e., the CREATE statement without any comments).
UPDATE #tblTextBasedObjects
SET ObjectTextWithoutComments = ObjectText
-- In this section we parse and exclude the comments in the CREATE
-- statement of all text-based objects. This is done in #tblTextBasedObjects
-- and has no effect on the underlying database objects.
SELECT @CurrObjectID = MIN(ObjectID)
FROM #tblTextBasedObjects
SELECT @CurrDataLength = ISNULL(DATALENGTH(ObjectText), 0)
FROM #tblTextBasedObjects
WHERE ObjectID = @CurrObjectID
WHILE @CurrObjectID IS NOT NULL
BEGIN
-- First, take out all comments of the type /* ... */
SELECT @i = PATINDEX('%/*%', ObjectTextWithoutComments)
FROM #tblTextBasedObjects
WHERE ObjectID = @CurrObjectID
SET @StopLoop = 0
-- Inner loop is used to take out all comments or the type /* ... */
-- and not only the first instance of such comment.
WHILE @i > 0 AND @StopLoop = 0
BEGIN
SET @Cnt = @i - 1
SET @i = @i + 1 -- takes care of the case /*/
SET @CommentCounter = 1
SET @InComment = 1
-- This loop searches for the closing pattern of the comment "*/",
-- and also considers nested comments.
WHILE @InComment = 1 AND @StopLoop = 0
BEGIN
SET @i = @i + 1
SELECT @tmpString = SUBSTRING(ObjectTextWithoutComments, @i, 2)
FROM #tblTextBasedObjects
WHERE ObjectID = @CurrObjectID
IF @tmpString = N'/*'
BEGIN
SET @CommentCounter = @CommentCounter + 1
SET @i = @i + 1
END
IF @tmpString = N'*/'
BEGIN
SET @CommentCounter = @CommentCounter - 1
-- This takes care of the scenario */*/
IF @CommentCounter > 0
SET @i = @i + 1
END
IF @CommentCounter = 0
SET @InComment = 0
IF @i = @CurrDataLength
SET @StopLoop = 1
END
SET @Diff = @i - @Cnt + 1
SET @tmpString = N''
-- Delete the comment from the CREATE statement stored in #tblTextBasedObjects
UPDATE #tblTextBasedObjects
SET ObjectTextWithoutComments = SUBSTRING(ObjectTextWithoutComments, 1, @Cnt) + SUBSTRING(ObjectTextWithoutComments, @Cnt + @Diff + 1, @CurrDataLength) -- @CurrTxtPtr @Cnt @Diff @tmpString
WHERE ObjectID = @CurrObjectID
SELECT @i = PATINDEX('%/*%', ObjectTextWithoutComments),
@CurrDataLength = (ISNULL(DATALENGTH(ObjectTextWithoutComments), 0))/2
FROM #tblTextBasedObjects
WHERE ObjectID = @CurrObjectID
END
-- Secondly, we parse out all comments that begin with --
SELECT @i = PATINDEX('%--%', ObjectTextWithoutComments),
@CurrDataLength = (ISNULL(DATALENGTH(ObjectTextWithoutComments), 0))/2
FROM #tblTextBasedObjects
WHERE ObjectID = @CurrObjectID
SET @StopLoop = 0
-- Inner loop is used to take out all comments or the type --
-- and not only the first instance of such comment.