-
Notifications
You must be signed in to change notification settings - Fork 1
/
sp_ctrl3.sql
2104 lines (1789 loc) · 107 KB
/
sp_ctrl3.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
/*
USE master
*/
IF (OBJECT_ID(N'dbo.sp_ctrl3') IS NULL)
--- Placeholder:
EXEC(N'CREATE PROCEDURE dbo.sp_ctrl3 AS ---');
GO
/*
Copyright Daniel Hutmacher under Creative Commons 4.0 license with attribution.
http://creativecommons.org/licenses/by/4.0/
Source: https://github.com/sqlsunday/sp_ctrl3
DISCLAIMER: This script may not be suitable to run in a production
environment. I cannot assume any responsibility regarding
the accuracy of the output information, performance
impacts on your server, or any other consequence. If
your juristiction does not allow for this kind of
waiver/disclaimer, or if you do not accept these terms,
you are NOT allowed to store, distribute or use this
code in any way.
USAGE: EXECUTE sp_ctrl3 {object name}
SHORTCUT: In SQL Server Management Studio, go to Tools -> Options
-> Environment -> Keyboard -> Query Shortcuts.
On a shortcut location of your choice, enter the following
code, with the trailing space, without the quotes:
"EXECUTE sp_ctrl3 ". To use, highlight the name of an object
and press that keyboard shortcut. You may have to open a new
query for the change to take effect. Also, objects denoted by
schema (with a dot) need to be enclosed in quotes for this
to work in older versions of SSMS.
VERSION: 2024-04-06
*/
ALTER PROCEDURE dbo.sp_ctrl3
@objname sysname
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;
SET STATISTICS XML, TIME, IO OFF;
SET DEADLOCK_PRIORITY LOW;
SET LOCK_TIMEOUT 500;
DECLARE @object_id int,
@object_id_str nvarchar(20),
@type char(2),
@database_id int,
@database sysname,
@compatibility_level tinyint,
@rowcount bigint=0,
@has_cols_or_params bit,
@has_indexes bit,
@has_foreign_keys bit,
@has_references bit,
@has_permissions bit,
@has_sql_module bit,
@has_data bit,
@has_policies bit,
@is_azure_sql_db bit=(CASE WHEN CAST(SERVERPROPERTY(N'Edition') AS varchar(100)) LIKE N'%Azure%' THEN 1 ELSE 0 END),
@is_tempdb bit=0,
@synonym_references nvarchar(1035)='',
@module_definition nvarchar(max),
@uses_ansi_nulls bit,
@uses_quoted_identifier bit,
@temp nvarchar(max),
@default_fill_factor tinyint=(SELECT TOP (1) CAST((CASE [value] WHEN 100 THEN 0 ELSE [value] END) AS tinyint)
FROM sys.configurations
WHERE [name] LIKE N'%fill factor%');
--- These are special (unicode) characters, used to display the graph output:
DECLARE @inf nchar(1)=NCHAR(8734), --- Infinity symbol
@hyph nchar(1)=NCHAR(8722), --- Hyphen
@pipe nchar(1)=NCHAR(8739), --- Pipe
@zero nchar(1)=NCHAR(176), --- Superscript "0".
@one nchar(1)=NCHAR(185), --- Superscript "1".
@lf nchar(1)=NCHAR(10), --- Line feed
@cr nchar(1)=NCHAR(13); --- Carriage return
--- If this is a synonym, follow it until we reach a base object.
--- (SQL Server does not currently allow recursive synonyms, but just in case.)
WHILE (@synonym_references IS NOT NULL) BEGIN;
SET @object_id=OBJECT_ID(@objname);
IF (@objname LIKE N'#%')
SELECT @is_tempdb=1, @object_id=OBJECT_ID(N'tempdb.dbo.'+@objname);
IF (@object_id IS NULL)
SELECT @object_id=tt.type_table_object_id
FROM sys.table_types AS tt
WHERE tt.user_type_id=TYPE_ID(@objname);
IF (@object_id IS NULL)
SET @synonym_references=NULL;
SELECT @database_id=database_id, @database=QUOTENAME([name]), @compatibility_level=[compatibility_level]
FROM sys.databases
WHERE @objname LIKE N'#%' AND [name]=N'tempdb' OR
[name]=PARSENAME(@objname, 3) OR
@objname NOT LIKE N'#%' AND database_id=DB_ID() AND PARSENAME(@objname, 3) IS NULL;
SET @object_id_str=CAST(@object_id AS nvarchar(20));
--- Is this a synonym, and if so, what base object does it reference?
SET @synonym_references=NULL;
SET @temp=N'SELECT @synonym_references=base_object_name FROM '+@database+N'.sys.synonyms WHERE [object_id]=@object_id;';
EXECUTE sys.sp_executesql
@temp,
N'@object_id int, @synonym_references nvarchar(1035) OUTPUT',
@object_id=@object_id,
@synonym_references=@synonym_references OUTPUT;
--- If yes, show header, update @objname, and restart the loop.
IF (@synonym_references IS NOT NULL) BEGIN;
SELECT OBJECT_SCHEMA_NAME(@object_id, @database_id) AS [Schema],
OBJECT_NAME(@object_id, @database_id) AS [Object],
N'Synonym' AS [Type],
@object_id AS [object_id],
@synonym_references AS [References];
SET @objname=@synonym_references COLLATE database_default;
END;
END;
-------------------------------------------------------------------------------
--- If database object isn't found, try a plaintext search instead.
IF (@object_id IS NULL) BEGIN;
DECLARE @search_results TABLE (
[type_desc] nvarchar(60) NOT NULL,
[schema_id] int NOT NULL,
major_id int NOT NULL,
minor_id int NULL,
index_id int NULL,
line int NULL,
[Definition] nvarchar(max) NULL,
row_count bigint NULL,
line_count int NULL,
_id int IDENTITY(1, 1) NOT NULL,
PRIMARY KEY CLUSTERED (major_id, _id)
);
--- T-SQL modules like stored procedures, views, function, triggers, etc.
WITH rcte AS (
SELECT [object_id], 1 AS line, CAST(NULL AS nvarchar(max)) AS [sql], REPLACE([definition], NCHAR(13)+NCHAR(10), NCHAR(13)) AS remain,
LEN([definition])-LEN(REPLACE([definition], CHAR(13), N'')) AS line_count
FROM sys.sql_modules
WHERE [definition] LIKE N'%'+@objname+N'%'
UNION ALL
SELECT rcte.[object_id],
CAST(rcte.line+LEN(x2.left_of_keyword)-LEN(REPLACE(REPLACE(x2.left_of_keyword, NCHAR(10), N''), NCHAR(13), N'')) AS int) AS line,
CAST(RIGHT(x2.left_of_keyword, PATINDEX(N'%['+NCHAR(10)+NCHAR(13)+N']%', REVERSE(x2.left_of_keyword)+NCHAR(10))-1)+
SUBSTRING(rcte.remain, x1.keyword_offset, x2.offset_to_next_line) AS nvarchar(max)) AS [sql],
CAST(SUBSTRING(rcte.remain, x1.keyword_offset+x2.offset_to_next_line, LEN(rcte.remain)) AS nvarchar(max)) AS remain,
rcte.line_count
FROM rcte
CROSS APPLY (
VALUES (
PATINDEX(N'%'+@objname+N'%', rcte.remain)
)) AS x1(keyword_offset)
CROSS APPLY (
VALUES (
LEFT(rcte.remain, x1.keyword_offset-1),
PATINDEX(N'%['+NCHAR(10)+NCHAR(13)+N']%', SUBSTRING(rcte.remain, x1.keyword_offset, LEN(rcte.remain))+NCHAR(10))-1
)) AS x2(left_of_keyword, offset_to_next_line)
WHERE x1.keyword_offset>0)
INSERT INTO @search_results ([type_desc], [schema_id], major_id, line, [Definition], line_count)
SELECT o.[type_desc], o.[schema_id], o.[object_id] AS major_id, rcte.line, rcte.[sql] AS [Definition], rcte.line_count
FROM rcte
INNER JOIN sys.all_objects AS o ON rcte.[object_id]=o.[object_id]
WHERE rcte.[sql] IS NOT NULL
OPTION (MAXRECURSION 0);
--- Columns or computed column definitions:
INSERT INTO @search_results ([type_desc], [schema_id], major_id, minor_id, [Definition])
SELECT t.[type_desc], t.[schema_id], t.[object_id] AS major_id, c.column_id AS minor_id,
COALESCE(cc.[name] COLLATE database_default+N' AS '+cc.[definition], c.[name], N'') AS [Definition]
FROM sys.tables AS t
INNER JOIN sys.all_columns AS c ON t.[object_id]=c.[object_id] AND c.[name] LIKE N'%'+@objname+N'%'
LEFT JOIN sys.computed_columns AS cc ON t.[object_id]=cc.[object_id] AND cc.[definition] LIKE N'%'+@objname+N'%'
LEFT JOIN sys.extended_properties AS ep ON ep.class=1 AND ep.major_id=t.[object_id] AND ep.minor_id=c.column_id AND ep.[name]=N'Description'
WHERE c.[name] LIKE N'%'+@objname+N'%' OR
cc.[definition] LIKE N'%'+@objname+N'%' OR
CAST(ep.[value] AS nvarchar(max)) LIKE N'%'+@objname+N'%';
--- Default constraints:
INSERT INTO @search_results ([type_desc], [schema_id], major_id, minor_id, [Definition])
SELECT c.[type_desc], o.[schema_id], o.[object_id] AS major_id, oc.column_id AS minor_id,
ISNULL(oc.[name]+N' ', N'')+N'CONSTRAINT '+c.[name]+N' DEFAULT '+c.[definition] AS [Definition]
FROM sys.default_constraints AS c
INNER JOIN sys.schemas AS s ON c.[schema_id]=s.[schema_id]
LEFT JOIN sys.all_objects AS o ON c.parent_object_id=o.[object_id]
LEFT JOIN sys.schemas AS os ON o.[schema_id]=os.[schema_id]
LEFT JOIN sys.all_columns AS oc ON c.parent_object_id=oc.[object_id] AND c.parent_column_id=oc.column_id
WHERE c.[name] LIKE N'%'+@objname+N'%' OR
c.[definition] LIKE N'%'+@objname+N'%';
--- Check constraints:
INSERT INTO @search_results ([type_desc], [schema_id], major_id, minor_id, [Definition])
SELECT c.[type_desc], o.[schema_id], o.[object_id] AS major_id, oc.column_id AS minor_id,
ISNULL(oc.[name]+N' ', N'')+N'CONSTRAINT '+c.[name]+N' CHECK '+c.[definition] AS [Definition]
FROM sys.check_constraints AS c
INNER JOIN sys.schemas AS s ON c.[schema_id]=s.[schema_id]
LEFT JOIN sys.all_objects AS o ON c.parent_object_id=o.[object_id]
LEFT JOIN sys.schemas AS os ON o.[schema_id]=os.[schema_id]
LEFT JOIN sys.all_columns AS oc ON c.parent_object_id=oc.[object_id] AND c.parent_column_id=oc.column_id
WHERE c.[name] LIKE N'%'+@objname+N'%' OR
c.[definition] LIKE N'%'+@objname+N'%';
--- Indexes and index filter definitions:
INSERT INTO @search_results ([type_desc], [schema_id], major_id, index_id, [Definition], row_count)
SELECT N'INDEX' AS [type_desc], o.[schema_id], o.[object_id] AS major_id, i.index_id,
(CASE WHEN i.is_unique=1 THEN N'UNIQUE ' ELSE N'' END)+i.[type_desc]+
(CASE WHEN i.index_id>0 THEN N' INDEX' ELSE N'' END)+
ISNULL(N' '+i.[name], N'')+
ISNULL(N' WHERE '+i.filter_definition, N'') AS [Definition],
(SELECT SUM(p.[rows])
FROM sys.partitions AS p
WHERE p.[object_id]=i.[object_id] AND p.index_id=i.index_id) AS row_count
FROM sys.indexes AS i
INNER JOIN sys.all_objects AS o ON i.[object_id]=o.[object_id]
INNER JOIN sys.schemas AS s ON o.[schema_id]=s.[schema_id]
WHERE i.[name] LIKE N'%'+@objname+N'%' OR
i.filter_definition LIKE N'%'+@objname+N'%';
--- Tables and objects:
INSERT INTO @search_results ([type_desc], [schema_id], major_id, row_count, line_count)
SELECT o.[type_desc], o.[schema_id], o.[object_id] AS major_id,
(SELECT SUM(p.[rows])
FROM sys.partitions AS p
WHERE p.[object_id]=o.[object_id] AND p.index_id IN (0, 1)) AS row_count,
(SELECT TOP (1) line_count
FROM @search_results
WHERE major_id=o.[object_id] AND line_count IS NOT NULL) AS line_count
FROM sys.all_objects AS o
LEFT JOIN sys.extended_properties AS ep ON ep.class=1 AND ep.major_id=o.[object_id] AND ep.minor_id=0 AND ep.[name]=N'Description'
WHERE o.parent_object_id=0 AND (
o.[object_id] IN (SELECT major_id FROM @search_results)
AND o.[object_id] NOT IN (SELECT major_id FROM @search_results WHERE major_id IS NOT NULL AND COALESCE(minor_id, index_id, line) IS NULL)
OR o.[name] LIKE N'%'+@objname+N'%'
OR CAST(ep.[value] AS nvarchar(max)) LIKE N'%'+@objname+N'%');
--- Schema
INSERT INTO @search_results ([type_desc], [schema_id], major_id, minor_id)
SELECT N'SCHEMA', s.[schema_id], 0, 0
FROM sys.schemas AS s
LEFT JOIN sys.extended_properties AS ep ON ep.class=3 AND ep.major_id=s.[schema_id] AND ep.minor_id=0 AND ep.[name]=N'Description'
WHERE s.[name] LIKE N'%'+@objname+N'%' OR
CAST(ep.[value] AS nvarchar(max)) LIKE N'%'+@objname+N'%'
OR s.[schema_id] IN (SELECT [schema_id] FROM @search_results)
AND s.[schema_id] NOT IN (SELECT [schema_id] FROM @search_results WHERE [type_desc]=N'SCHEMA');
--- Output the results in a fancypants ASCII graph:
SELECT (CASE WHEN o._ordinal=0 THEN s.[name] ELSE N'' END) AS [Schema],
ISNULL((CASE WHEN x._ordinal=0 THEN o.[type_desc] ELSE N'' END), N'') AS [Object type],
ISNULL((CASE WHEN x._ordinal=0 THEN s.[name]+N'.'+o.[name] WHEN x._ordinal=1 AND x._count>1 THEN N'/' WHEN x._ordinal=x._count THEN N'\' ELSE N'|' END), N'') AS [Object],
(CASE WHEN x._ordinal=0 THEN COALESCE(REPLACE(CONVERT(varchar(20), CAST(o.line_count AS money), 1), '.00', '')+' lines',
REPLACE(CONVERT(varchar(20), CAST(o.row_count AS money), 1), '.00', '')+' rows', '')
WHEN x.index_id IS NOT NULL THEN COALESCE(REPLACE(CONVERT(varchar(20), CAST(x.row_count AS money), 1), '.00', '')+' rows', '')
ELSE '' END) AS [Size],
ISNULL(STR(x.line, 10, 0), N'') AS [Line no],
ISNULL(x.[Definition], N'') AS [Definition],
ISNULL((CASE WHEN x._ordinal>0 THEN x.[Description]
WHEN x._ordinal=0 THEN o.[Description]
WHEN o._ordinal=0 THEN ep.[value] END), N'') AS [Description]
FROM @search_results AS x1
INNER JOIN sys.schemas AS s ON x1.[schema_id]=s.[schema_id]
LEFT JOIN sys.extended_properties AS ep ON ep.class=3 AND ep.major_id=s.[schema_id] AND ep.minor_id=0 AND ep.[name]=N'Description'
--- For each schema, return one blank offset row and the objects for that schema:
OUTER APPLY (
SELECT ROW_NUMBER() OVER (PARTITION BY s.[schema_id] ORDER BY o.[name]) AS _ordinal,
COUNT(*) OVER (PARTITION BY s.[schema_id]) AS _count,
o.[object_id], o.[name], o.[type_desc], ep.[value] AS [Description],
row_count, line_count
FROM @search_results AS res
INNER JOIN sys.objects AS o ON res.major_id=o.[object_id]
LEFT JOIN sys.extended_properties AS ep ON ep.class=1 AND ep.major_id=res.major_id AND ep.minor_id=0 AND ep.[name]=N'Description'
WHERE res.[schema_id]=s.[schema_id] AND COALESCE(res.minor_id, res.index_id, res.line) IS NULL
UNION ALL
SELECT 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL
) AS o
--- .. and for each object, return a blank offset row and all of the lines/columns/etc for that object:
OUTER APPLY (
SELECT ROW_NUMBER() OVER (PARTITION BY res.major_id ORDER BY res.minor_id) AS _ordinal,
COUNT(*) OVER (PARTITION BY res.major_id) AS _count,
res.line,
res.minor_id, res.index_id, res.row_count,
res.[Definition], ep.[value] AS [Description]
FROM @search_results AS res
LEFT JOIN sys.extended_properties AS ep ON ep.class=1 AND ep.major_id=res.major_id AND ep.minor_id=res.minor_id AND ep.[name]=N'Description'
WHERE res.major_id=o.[object_id] AND COALESCE(res.minor_id, res.index_id, res.line) IS NOT NULL
UNION ALL
SELECT 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL
) AS x
WHERE x1.major_id=0
ORDER BY s.[name], o._ordinal, x._ordinal;
RETURN;
/* ,
search AS (
)
SELECT class, parent_class, parent_id, major_id, minor_id, ordinal, [Type], [Line no], [Definition], Size
INTO #search_results
FROM search
OPTION (MAXRECURSION 0);
INSERT INTO #search_results (class, parent_class, parent_id, major_id, minor_id, ordinal, [Type], [Line no], [Definition], Size)
SELECT 1 AS class, 3 AS parent_class, [schema_id] AS parent_id, [object_id] AS major_id, 0 AS minor_id, 0 AS ordinal,
t.[type_desc] AS [Type], '' AS [Line no],
NULL AS [Definition],
ISNULL((SELECT REPLACE(CONVERT(varchar(20), CAST(NULLIF(SUM(p.[rows]), 0) AS money), 1), '.00', '')+' rows'
FROM sys.partitions AS p
WHERE p.[object_id]=t.[object_id] AND p.index_id IN (0, 1)), '(empty)') AS [Size]
FROM sys.tables AS t
WHERE t.[object_id] IN (SELECT major_id FROM #search_results WHERE class IN (-1, 51))
AND t.[object_id] NOT IN (SELECT major_id FROM #search_results WHERE class=1);
INSERT INTO #search_results (class, parent_id, major_id, minor_id, ordinal, [Type], [Line no], [Definition], Size)
SELECT 3 AS class, NULL AS parent_id, s.[schema_id] AS major_id, 0 AS minor_id, 0 AS ordinal,
N'SCHEMA' AS [Type], '' AS [Line no],
N'' AS [Definition], '' AS [Size]
FROM sys.schemas AS s
WHERE s.[schema_id] IN (SELECT parent_id FROM #search_results WHERE class=1)
AND s.[schema_id] NOT IN (SELECT major_id FROM #search_results WHERE class=3);
*/
RETURN;
END;
-------------------------------------------------------------------------------
--- Table variables to hold copies of system DMVs. The reason we use temp tables
--- is to be able to collect this data from the current database or from
--- tempdb (if it's a temp table)
DECLARE @sysobjects TABLE (
[schema_id] int NOT NULL,
[object_id] int NOT NULL,
principal_id int NULL,
[type] char(2) COLLATE database_default NOT NULL,
[type_desc] nvarchar(60) COLLATE database_default NOT NULL,
[name] sysname COLLATE database_default NOT NULL,
is_memory_optimized bit NOT NULL,
durability_desc nvarchar(60) COLLATE database_default NULL,
temporal_type_desc nvarchar(60) COLLATE database_default NULL,
history_table_id int NULL,
is_change_tracked bit NOT NULL,
is_track_columns_updated_on bit NOT NULL,
min_valid_version bigint NULL,
PRIMARY KEY CLUSTERED ([object_id])
);
DECLARE @sysschemas TABLE (
[schema_id] int NOT NULL,
principal_id int NOT NULL,
name sysname COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED ([schema_id])
);
DECLARE @syscolumns TABLE (
[object_id] int NOT NULL,
column_id int NOT NULL,
[name] sysname COLLATE database_default NOT NULL,
user_type_id int NOT NULL,
system_type_id int NOT NULL,
max_length smallint NOT NULL,
[precision] tinyint NOT NULL,
scale tinyint NOT NULL,
is_sparse bit NULL,
is_nullable bit NULL,
collation_name sysname COLLATE database_default NULL,
is_ansi_padded bit NOT NULL,
xml_collection_id int NOT NULL,
default_object_id int NOT NULL,
seed_value sql_variant NULL,
increment_value sql_variant NULL,
[definition] nvarchar(max) COLLATE database_default NULL,
is_persisted bit NULL,
[type_name] sysname COLLATE database_default NOT NULL,
default_name sysname COLLATE database_default NULL,
default_is_system_named bit NULL,
current_value sql_variant NULL,
max_alloc_size int NULL,
generated_always_type_desc nvarchar(60) COLLATE database_default NULL,
is_hidden bit NULL,
PRIMARY KEY CLUSTERED ([object_id], column_id)
);
DECLARE @sysparameters TABLE (
parameter_id int NOT NULL,
name sysname COLLATE database_default NOT NULL,
user_type_id int NOT NULL,
system_type_id int NOT NULL,
max_length smallint NOT NULL,
[precision] tinyint NOT NULL,
scale tinyint NOT NULL,
is_nullable bit NULL,
xml_collection_id int NOT NULL,
is_output bit NOT NULL,
is_readonly bit NOT NULL,
is_table_type bit NOT NULL,
[type_name] sysname COLLATE database_default NOT NULL,
tbl_type_cols varchar(max) COLLATE database_default NULL,
PRIMARY KEY CLUSTERED (parameter_id)
);
DECLARE @sysindexes TABLE (
[object_id] int NOT NULL,
index_id int NOT NULL,
[name] sysname COLLATE database_default NULL,
[type] tinyint NOT NULL,
[type_desc] nvarchar(120) COLLATE database_default NULL,
data_space_id int NULL,
is_primary_key bit NULL,
is_unique_constraint bit NULL,
is_unique bit NULL,
filter_definition nvarchar(max) COLLATE database_default NULL,
fill_factor tinyint NOT NULL,
[allow_row_locks] bit NULL,
[allow_page_locks] bit NULL,
is_padded bit NULL,
has_filter bit NULL,
is_system_named bit NOT NULL,
[bucket_count] bigint NULL,
[compression_delay] int NULL,
PRIMARY KEY CLUSTERED ([object_id], index_id)
);
DECLARE @sysindexcolumns TABLE (
[object_id] int NOT NULL,
index_id int NOT NULL,
index_column_id int NOT NULL,
column_id int NOT NULL,
key_ordinal tinyint NOT NULL,
partition_ordinal tinyint NOT NULL,
is_descending_key bit NULL,
is_included_column bit NULL,
PRIMARY KEY CLUSTERED ([object_id], index_id, key_ordinal, index_column_id)
);
DECLARE @sysforeignkeys TABLE (
[object_id] int NOT NULL,
name sysname COLLATE database_default NOT NULL,
parent_object_id int NOT NULL,
referenced_object_id int NOT NULL,
delete_referential_action_desc nvarchar(120) COLLATE database_default NULL,
update_referential_action_desc nvarchar(120) COLLATE database_default NULL,
is_system_named bit NOT NULL,
is_disabled bit NOT NULL,
is_not_trusted bit NOT NULL,
PRIMARY KEY CLUSTERED ([object_id])
);
DECLARE @sysforeignkeycols TABLE (
constraint_object_id int NOT NULL,
constraint_column_id int NOT NULL,
parent_object_id int NOT NULL,
parent_column_id int NOT NULL,
referenced_object_id int NOT NULL,
referenced_column_id int NOT NULL,
PRIMARY KEY CLUSTERED (constraint_object_id, constraint_column_id)
);
DECLARE @xmlschemacollections TABLE (
xml_collection_id int NOT NULL,
[schema_id] int NOT NULL,
name sysname COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED (xml_collection_id)
);
DECLARE @sysdataspaces TABLE (
data_space_id int NOT NULL,
name sysname COLLATE database_default NOT NULL,
[type] char(2) COLLATE database_default NOT NULL,
is_default bit NOT NULL,
PRIMARY KEY CLUSTERED (data_space_id)
);
DECLARE @sysdatabaseprincipals TABLE (
principal_id int NOT NULL,
name sysname COLLATE database_default NOT NULL
);
DECLARE @sysexprdependencies TABLE (
referencing_id int NOT NULL,
referenced_id int NOT NULL,
is_schema_bound_reference bit NOT NULL,
PRIMARY KEY CLUSTERED (referencing_id, referenced_id)
);
DECLARE @syspartitions TABLE (
[partition_id] bigint NULL,
[object_id] int NOT NULL,
index_id int NOT NULL,
partition_number int NOT NULL,
[rows] bigint NULL,
data_compression_desc nvarchar(120) COLLATE database_default NOT NULL,
xml_compression_desc varchar(3) COLLATE database_default NULL,
boundary_value_on_right bit NULL,
boundary nvarchar(max) NULL,
boundary_type sysname NULL,
discrete_boundary bit NULL,
PRIMARY KEY CLUSTERED ([object_id], index_id, partition_number)
);
DECLARE @index_physical_stats TABLE (
[object_id] int NOT NULL,
index_id int NOT NULL,
partition_number int NOT NULL,
effective_fill_factor numeric(5, 2) NULL,
PRIMARY KEY CLUSTERED ([object_id], index_id, partition_number)
);
DECLARE @syspartitionstats TABLE (
[partition_id] bigint NOT NULL,
row_count bigint NULL,
in_row_used_page_count bigint NULL,
reserved_page_count bigint NULL,
row_overflow_used_page_count bigint NULL,
lob_used_page_count bigint NULL,
used_page_count bigint NULL,
PRIMARY KEY CLUSTERED ([partition_id])
);
DECLARE @destination_data_spaces TABLE (
partition_scheme_id int NOT NULL,
partition_number int NOT NULL,
data_space_id int NOT NULL,
PRIMARY KEY CLUSTERED (partition_scheme_id, partition_number)
);
DECLARE @columnstore_rowgroups TABLE (
[object_id] int NOT NULL,
index_id int NOT NULL,
partition_number int NOT NULL,
[state] tinyint NOT NULL,
total_rows bigint NOT NULL,
size_in_bytes bigint NOT NULL,
PRIMARY KEY CLUSTERED ([object_id], index_id, partition_number, [state])
);
DECLARE @sysdatabasepermissions TABLE (
class tinyint NOT NULL,
class_desc nvarchar(120) COLLATE database_default NULL,
major_id int NOT NULL,
minor_id int NOT NULL,
grantee_principal_id int NOT NULL,
grantor_principal_id int NOT NULL,
[type] char(4) COLLATE database_default NOT NULL,
[permission_name] nvarchar(256) COLLATE database_default NULL,
[state] char(1) COLLATE database_default NOT NULL,
state_desc nvarchar(120) COLLATE database_default NULL,
PRIMARY KEY CLUSTERED (class, major_id, minor_id, [type], [state], grantee_principal_id)
);
DECLARE @signatures TABLE (
src nvarchar(20) COLLATE database_default NOT NULL,
[name] sysname COLLATE database_default NOT NULL,
encryption_type_desc varchar(20) COLLATE database_default NULL,
[type_desc] nvarchar(60) COLLATE database_default NOT NULL,
major_id int NOT NULL
);
DECLARE @references TABLE (
parent_id int NOT NULL, --- object_id of referencing object
parent_name varchar(255) COLLATE database_default NOT NULL, -- Name of referencing object
child_id int NOT NULL, --- object_id of referenced object
child_name varchar(255) COLLATE database_default NOT NULL, -- Name of referenced object
is_schemabound bit, --- Is this relation schemabound?
is_foreign_key bit, --- Is this relation a foreign key constraint? (If not, it's an SQL module)
parent_row smallint NOT NULL, --- Parent ordinal (this child)
parent_count smallint NOT NULL, --- Number of parents (this child)
child_row smallint NOT NULL, --- Child ordinal (this parent)
child_count smallint NOT NULL, --- Number of children (this parent)
is_unique bit NOT NULL, --- If the combination of referencing columns is unique
is_nullable bit NOT NULL, --- If the referencing column allows nulls
PRIMARY KEY CLUSTERED (parent_id, child_id),
UNIQUE (parent_id, child_row),
UNIQUE (child_id, parent_row)
);
DECLARE @syssecuritypolicies TABLE (
security_policy_id int NOT NULL,
security_predicate_id int NOT NULL,
predicate_type_desc nvarchar(60) COLLATE database_default NOT NULL,
predicate_definition nvarchar(max) COLLATE database_default NOT NULL,
is_enabled bit NOT NULL,
is_schema_bound bit NOT NULL,
PRIMARY KEY CLUSTERED (security_policy_id, security_predicate_id)
);
DECLARE @syssqlmodules TABLE (
[definition] nvarchar(max) COLLATE database_default NULL,
uses_ansi_nulls bit NULL,
uses_quoted_identifier bit NULL,
is_schema_bound bit NULL,
uses_native_compilation bit NULL
);
DECLARE @systriggers TABLE (
[object_id] int NOT NULL,
name sysname COLLATE database_default NOT NULL,
is_disabled bit NOT NULL,
is_instead_of_trigger bit NOT NULL,
[trigger_events] sysname COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED ([object_id])
);
/*
DECLARE @plans TABLE (
_id int IDENTITY(1, 1) NOT NULL,
plan_generation_num bigint NOT NULL,
query_plan xml NULL,
execution_count bigint NOT NULL,
last_execution_time datetime NULL,
PRIMARY KEY CLUSTERED (plan_generation_num, _id)
);
*/
DECLARE @spt_values_O9T TABLE (
[name] nvarchar(50) COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED ([name])
);
DECLARE @definition TABLE (
id int NOT NULL,
[definition] nvarchar(max) COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED (id)
);
DECLARE @reserved_keywords TABLE (
keyword sysname COLLATE database_default NOT NULL,
PRIMARY KEY CLUSTERED (keyword)
);
DECLARE @extended_properties TABLE (
[object_id] int NOT NULL,
column_id int NOT NULL,
[name] sysname COLLATE database_default NOT NULL,
[value] sql_variant NULL
PRIMARY KEY CLUSTERED ([object_id], column_id, [name])
);
-------------------------------------------------------------------------------
--- Populate DMV table variables:
IF (@is_azure_sql_db=1)
INSERT INTO @spt_values_O9T ([name])
EXEC(N'
SELECT DISTINCT [type]+N'': ''+LOWER([type_desc])
FROM sys.objects');
IF (@is_azure_sql_db=0)
INSERT INTO @spt_values_O9T ([name])
EXEC(N'
SELECT [name]
FROM master.dbo.spt_values
WHERE [type]=N''O9T''');
SET @temp=N'
SELECT ISNULL(tt.[schema_id], o.[schema_id]), o.[object_id], o.principal_id, o.[type], o.[type_desc], ISNULL(tt.[name], o.[name]),
'+(CASE WHEN @compatibility_level>=120 THEN N'ISNULL(t.is_memory_optimized, 0), t.durability_desc' ELSE N'0, NULL' END)+N',
'+(CASE WHEN @compatibility_level>=130 THEN N't.temporal_type_desc, t.history_table_id' ELSE N'NULL, NULL' END)+N',
(CASE WHEN ct.[object_id] IS NOT NULL THEN 1 ELSE 0 END), ISNULL(ct.is_track_columns_updated_on, 0), ct.min_valid_version
FROM '+@database+N'.sys.all_objects AS o
LEFT JOIN '+@database+N'.sys.tables AS t ON o.[object_id]=t.[object_id]
LEFT JOIN '+@database+N'.sys.table_types AS tt ON tt.type_table_object_id=o.[object_id]
LEFT JOIN '+@database+N'.sys.change_tracking_tables AS ct ON t.[object_id]=ct.[object_id]'
INSERT INTO @sysobjects
EXEC(@temp);
INSERT INTO @sysschemas
EXEC(N'
SELECT [schema_id], principal_id, name
FROM '+@database+N'.sys.schemas');
SET @temp=(CASE
WHEN @compatibility_level>=130
THEN N'c.generated_always_type_desc, c.is_hidden'
ELSE N'NULL, NULL' END);
INSERT INTO @syscolumns
EXEC(N'
SELECT c.[object_id], c.column_id, c.[name], c.user_type_id, c.system_type_id,
c.max_length, c.[precision], c.scale, c.is_sparse, c.is_nullable,
c.collation_name, c.is_ansi_padded, c.xml_collection_id, c.default_object_id,
ic.seed_value, ic.increment_value, ISNULL(cc.[definition], d.[definition]), cc.is_persisted,
t.[name] AS [type_name], d.[name] AS default_name,
d.is_system_named AS default_is_system_named, NULL AS current_value,
(CASE WHEN st.[name]IN (N''bit'', N''tinyint'') THEN 1
WHEN st.[name]=N''smallint'' THEN 2
WHEN st.[name]=N''date'' THEN 3
WHEN st.[name] IN (N''int'', N''smalldatetime'', N''smallmoney'') THEN 4
WHEN st.[name] IN (N''bigint'', N''money'', N''timestamp'', N''datetime'') THEN 8
WHEN st.[name]=N''datetime2'' AND c.scale BETWEEN 1 AND 2 THEN 6
WHEN st.[name]=N''datetime2'' AND c.scale BETWEEN 3 AND 4 THEN 7
WHEN st.[name]=N''datetime2'' AND c.scale BETWEEN 5 AND 7 THEN 8
WHEN st.[name]=N''datetimeoffset'' AND c.scale BETWEEN 0 AND 2 THEN 8
WHEN st.[name]=N''datetimeoffset'' AND c.scale BETWEEN 3 AND 4 THEN 9
WHEN st.[name]=N''datetimeoffset'' AND c.scale BETWEEN 5 AND 7 THEN 10
WHEN st.[name] IN (N''decimal'', N''numeric'') AND c.[precision] BETWEEN 1 AND 9 THEN 5
WHEN st.[name] IN (N''decimal'', N''numeric'') AND c.[precision] BETWEEN 10 AND 19 THEN 9
WHEN st.[name] IN (N''decimal'', N''numeric'') AND c.[precision] BETWEEN 20 AND 28 THEN 13
WHEN st.[name] IN (N''decimal'', N''numeric'') AND c.[precision] BETWEEN 29 AND 38 THEN 17
WHEN st.[name]=N''real'' THEN 4
WHEN st.[name]=N''float'' AND c.[precision]<=24 THEN 4
WHEN st.[name]=N''float'' AND c.[precision]>24 THEN 8
WHEN st.[name]=N''time'' AND c.[scale] BETWEEN 0 AND 2 THEN 3
WHEN st.[name]=N''time'' AND c.[scale] BETWEEN 3 AND 4 THEN 4
WHEN st.[name]=N''time'' AND c.[scale] BETWEEN 5 AND 7 THEN 5
WHEN st.[name] IN (N''binary'', N''varbinary'', N''char'', N''nchar'', N''varchar'', N''nvarchar'', N''sysname'') THEN NULLIF(c.max_length, -1)
WHEN st.[name]=N''uniqueidentifier'' THEN 16
END) AS max_alloc_size,
'+@temp+N'
FROM '+@database+N'.sys.all_columns AS c
LEFT JOIN '+@database+N'.sys.identity_columns AS ic ON c.[object_id]=ic.[object_id] AND c.column_id=ic.column_id
LEFT JOIN '+@database+N'.sys.computed_columns AS cc ON c.[object_id]=cc.[object_id] AND c.column_id=cc.column_id
LEFT JOIN '+@database+N'.sys.types AS t ON c.user_type_id=t.user_type_id
LEFT JOIN '+@database+N'.sys.types AS st ON c.system_type_id=st.user_type_id
LEFT JOIN '+@database+N'.sys.default_constraints AS d ON d.[object_id]=c.default_object_id');
BEGIN TRY;
INSERT INTO @syscolumns
EXEC(N'
SELECT s.[object_id], 1 AS column_id, s.[name], s.user_type_id, s.system_type_id,
8 AS max_length, s.[precision], s.scale, 0 AS is_sparse, 0 AS is_nullable,
NULL AS collation_name, 0 AS is_ansi_padded, 0 AS xml_collection_id, 0 AS default_object_id,
s.start_value AS seed_value, s.increment AS increment_value,
ISNULL(N'' MINVALUE ''+CAST(NULLIF(s.minimum_value, (CASE st.[name]
WHEN N''tinyint'' THEN 0
WHEN N''smallint'' THEN -32768
WHEN N''int'' THEN -2147483648
WHEN N''bigint'' THEN -9223372036854775808
END)) AS nvarchar(40)), N'''')+
ISNULL(N'' MAXVALUE ''+CAST(NULLIF(s.maximum_value, (CASE st.[name]
WHEN N''tinyint'' THEN 255
WHEN N''smallint'' THEN 32767
WHEN N''int'' THEN 2147483647
WHEN N''bigint'' THEN 9223372036854775807
END)) AS nvarchar(40)), N'''')+
(CASE WHEN s.is_cycling=1 THEN N'' CYCLE'' ELSE N'''' END)+
(CASE WHEN s.is_cached=0 THEN N'' NOCACHE''
WHEN s.is_cached=1 THEN ISNULL(N''CACHE ''+CAST(s.cache_size AS nvarchar(20)), '''')
END) AS [definition], 0 AS is_persisted,
t.[name] AS [type_name], NULL AS default_name, 1 AS default_is_system_named, s.current_value, NULL, NULL, NULL
FROM '+@database+N'.sys.sequences AS s
LEFT JOIN '+@database+N'.sys.types AS t ON s.user_type_id=t.user_type_id
LEFT JOIN '+@database+N'.sys.types AS st ON s.system_type_id=st.user_type_id
');
END TRY
BEGIN CATCH;
PRINT 'sys.sequences could not be loaded.';
END CATCH;
SET @temp=(CASE WHEN SERVERPROPERTY('ProductVersion')>=N'12' THEN N'p.is_nullable' ELSE N'1' END);
INSERT INTO @sysparameters
EXEC(N'
SELECT p.parameter_id, p.[name], p.user_type_id, p.system_type_id, p.max_length, p.[precision],
p.scale, '+@temp+N', p.xml_collection_id, p.is_output, p.is_readonly, t.is_table_type,
ISNULL(s.[name]+N''.'', N'''')+t.[name] AS [type_name],
N''(''+SUBSTRING(CAST((SELECT N'', ''+ttc.[name]
FROM '+@database+N'.sys.all_columns AS ttc
WHERE ttc.[object_id]=tt.type_table_object_id
ORDER BY ttc.column_id
FOR XML PATH(N''''), TYPE) AS varchar(max)), 3, 8000)+N'')'' AS tbl_type_cols
FROM '+@database+N'.sys.all_parameters AS p
LEFT JOIN '+@database+N'.sys.types AS t ON p.user_type_id=t.user_type_id
LEFT JOIN '+@database+N'.sys.table_types AS tt ON t.user_type_id=tt.user_type_id
LEFT JOIN '+@database+N'.sys.schemas AS s ON t.is_table_type=1 AND t.[schema_id]=s.[schema_id]
WHERE p.[object_id]='+@object_id_str);
SET @temp=(CASE WHEN SERVERPROPERTY('ProductVersion')>=N'13' THEN N'ix.[compression_delay]' ELSE N'NULL' END);
INSERT INTO @sysindexes
EXEC(N'
SELECT ix.[object_id], ix.index_id, ix.[name], ix.[type], ix.[type_desc], ix.data_space_id,
ix.is_primary_key, ix.is_unique_constraint, ix.is_unique, ix.filter_definition,
ix.fill_factor, ix.[allow_row_locks], ix.[allow_page_locks], ix.is_padded, ix.has_filter,
ISNULL(kc.is_system_named, 0), NULL, '+@temp+N'
FROM '+@database+N'.sys.indexes AS ix
LEFT JOIN '+@database+N'.sys.key_constraints AS kc ON ix.[object_id]=kc.parent_object_id AND ix.[name]=kc.[name]
WHERE ix.is_hypothetical=0 AND ix.[type_desc] NOT LIKE N''%HASH%''');
IF (@compatibility_level>=120)
INSERT INTO @sysindexes
EXEC(N'
SELECT ix.[object_id], ix.index_id, ix.[name], ix.[type], ix.[type_desc], ix.data_space_id,
ix.is_primary_key, ix.is_unique_constraint, ix.is_unique, ix.filter_definition,
ix.fill_factor, ix.[allow_row_locks], ix.[allow_page_locks], ix.is_padded, ix.has_filter,
ISNULL(kc.is_system_named, 0), ix.[bucket_count], NULL
FROM '+@database+N'.sys.hash_indexes AS ix
LEFT JOIN '+@database+N'.sys.key_constraints AS kc ON ix.[object_id]=kc.parent_object_id AND ix.[name]=kc.[name]
WHERE ix.is_hypothetical=0');
INSERT INTO @sysindexcolumns
EXEC(N'
SELECT [object_id], index_id, index_column_id, column_id, key_ordinal,
partition_ordinal, is_descending_key, is_included_column
FROM '+@database+N'.sys.index_columns');
INSERT INTO @sysforeignkeys
EXEC(N'
SELECT [object_id], name, parent_object_id, referenced_object_id,
delete_referential_action_desc, update_referential_action_desc,
is_system_named, is_disabled, is_not_trusted
FROM '+@database+N'.sys.foreign_keys');
INSERT INTO @sysforeignkeycols
EXEC(N'
SELECT constraint_object_id, constraint_column_id, parent_object_id,
parent_column_id, referenced_object_id, referenced_column_id
FROM '+@database+N'.sys.foreign_key_columns');
INSERT INTO @extended_properties
EXEC(N'
SELECT major_id, minor_id, [name], [value]
FROM '+@database+N'.sys.extended_properties
WHERE class=1;');
INSERT INTO @xmlschemacollections
EXEC(N'
SELECT xml_collection_id, [schema_id], name
FROM '+@database+N'.sys.xml_schema_collections');
INSERT INTO @sysdataspaces
EXEC(N'
SELECT data_space_id, name, [type], is_default
FROM '+@database+N'.sys.data_spaces');
INSERT INTO @sysdatabaseprincipals
EXEC(N'
SELECT principal_id, name
FROM '+@database+N'.sys.database_principals');
SET @temp=N'
SELECT [definition], uses_ansi_nulls, uses_quoted_identifier, is_schema_bound'+(CASE WHEN @compatibility_level>=120 THEN N', uses_native_compilation' ELSE N', NULL' END)+N'
FROM '+@database+N'.sys.sql_modules
WHERE [object_id]='+@object_id_str
INSERT INTO @syssqlmodules
EXEC(@temp);
SELECT @module_definition=[definition],
@uses_ansi_nulls=uses_ansi_nulls,
@uses_quoted_identifier=uses_quoted_identifier
FROM @syssqlmodules;
BEGIN TRY;
INSERT INTO @sysexprdependencies
EXEC(N'
SELECT referencing_id,
referenced_id,
is_schema_bound_reference
FROM (
SELECT DISTINCT d.referencing_id,
COALESCE(ct.type_table_object_id,
d.referenced_id,
(CASE WHEN d.referenced_server_name IS NULL AND d.referenced_database_name IS NULL
THEN OBJECT_ID(ISNULL(QUOTENAME(referenced_schema_name)+N''.'', N'''')+QUOTENAME(d.referenced_entity_name)) END)) AS referenced_id,
(CASE WHEN ct.user_type_id IS NOT NULL THEN 1 ELSE d.is_schema_bound_reference END) AS is_schema_bound_reference
FROM '+@database+N'.sys.sql_expression_dependencies AS d
LEFT JOIN '+@database+N'.sys.table_types AS ct ON d.referenced_class=6 AND d.referenced_id=ct.user_type_id
WHERE d.referencing_class=1 AND
d.referenced_class IN (1, 6)
) AS sub
WHERE referenced_id IS NOT NULL;');
END TRY
BEGIN CATCH;
PRINT 'Problem compiling expression dependencies: '+ERROR_MESSAGE();
END CATCH;
SET @temp=N'
SELECT p.[partition_id], p.[object_id], p.index_id, p.partition_number, p.[rows], p.data_compression_desc,
'+(CASE WHEN @compatibility_level>=160 THEN N'p.xml_compression_desc' ELSE N'NULL' END)+N', pf.boundary_value_on_right, prv.boundary, prv.boundary_type, 0
FROM '+@database+N'.sys.partitions AS p
LEFT JOIN '+@database+N'.sys.indexes AS i ON p.[object_id]=i.[object_id] AND p.index_id=i.index_id AND p.[object_id]='+@object_id_str+N'
LEFT JOIN '+@database+N'.sys.partition_schemes AS ps ON i.data_space_id=ps.data_space_id
LEFT JOIN '+@database+N'.sys.partition_functions AS pf ON ps.function_id=pf.function_id
LEFT JOIN (
SELECT function_id, boundary_id, CAST(SQL_VARIANT_PROPERTY([value], N''BaseType'') AS sysname) AS boundary_type,
(CASE
WHEN CAST(SQL_VARIANT_PROPERTY([value], N''BaseType'') AS sysname)=N''date'' THEN LEFT(CONVERT(nvarchar(max), [value], 120), 10)
WHEN CAST(SQL_VARIANT_PROPERTY([value], N''BaseType'') AS sysname) LIKE N''%datetime%'' THEN CONVERT(nvarchar(max), [value], 120)
ELSE CAST([value] AS nvarchar(max)) END) AS boundary
FROM '+@database+N'.sys.partition_range_values
WHERE parameter_id=1
) AS prv ON pf.function_id=prv.function_id AND p.partition_number=prv.boundary_id'
INSERT INTO @syspartitions
EXEC(@temp);
-- Does this partition have a discrete boundary, i.e. can it only contain a single boundary value?
-- This applies to discrete datatypes, like integers, dates, etc.
UPDATE sub
SET sub.discrete_boundary=1
FROM (
SELECT discrete_boundary,
TRY_CAST(LAG(boundary, 1) OVER (PARTITION BY [object_id], index_id ORDER BY partition_number) AS bigint) AS a,
TRY_CAST(boundary AS bigint) AS b,
TRY_CAST(LEAD(boundary, 1) OVER (PARTITION BY [object_id], index_id ORDER BY partition_number) AS bigint) AS c
FROM @syspartitions
WHERE boundary_type IN (N'bit', N'tinyint', N'smallint', N'int', N'bigint')
) AS sub
WHERE a+1=b AND b+1=ISNULL(c, b+1);
UPDATE sub
SET sub.discrete_boundary=1
FROM (
SELECT discrete_boundary,
TRY_CAST(LAG(boundary, 1) OVER (PARTITION BY [object_id], index_id ORDER BY partition_number) AS date) AS a,
TRY_CAST(boundary AS date) AS b,
TRY_CAST(LEAD(boundary, 1) OVER (PARTITION BY [object_id], index_id ORDER BY partition_number) AS date) AS c
FROM @syspartitions
WHERE boundary_type IN (N'date')
) AS sub
WHERE DATEADD(day, 1, a)=b AND DATEADD(day, 1, b)=ISNULL(c, DATEADD(day, 1, b));
BEGIN TRY;
INSERT INTO @syspartitionstats
EXEC(N'
SELECT ps.[partition_id], ps.row_count, ps.in_row_used_page_count, ps.reserved_page_count,
ps.row_overflow_used_page_count, ps.lob_used_page_count, ps.used_page_count
FROM '+@database+N'.sys.dm_db_partition_stats AS ps
INNER JOIN '+@database+N'.sys.partitions AS p ON ps.[partition_id]=p.[partition_id]');
END TRY
BEGIN CATCH;
PRINT 'Problem compiling partition stats: '+ERROR_MESSAGE();
END CATCH;
BEGIN TRY;
SET @temp=N'
SELECT [object_id], index_id, partition_number,
ISNULL(SUM(avg_page_space_used_in_percent*page_count)/NULLIF(SUM(page_count), 0), 0)
FROM sys.dm_db_index_physical_stats('+CAST(@database_id AS nvarchar(10))+N', '+@object_id_str+N', DEFAULT, DEFAULT, ''SAMPLED'') AS ips
GROUP BY [object_id], index_id, partition_number';
INSERT INTO @index_physical_stats
EXEC(@temp);
END TRY
BEGIN CATCH;
PRINT 'Problem compiling physical index stats: '+ERROR_MESSAGE();
END CATCH;
BEGIN TRY;
INSERT INTO @destination_data_spaces
EXEC(N'
SELECT partition_scheme_id, destination_id AS partition_number, data_space_id