-
Notifications
You must be signed in to change notification settings - Fork 15
/
SqlServerIssue.dbs
2207 lines (2207 loc) · 121 KB
/
SqlServerIssue.dbs
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
<?xml version="1.0" encoding="UTF-8" ?>
<project name="SqlServer" id="Project-15a" database="SqlServer" >
<schema name="dbo" catalogname="master" >
<comment><![CDATA[bbb]]></comment>
<table name="DOT_Candidat" row_count="2" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<index name="PK__DOT_Cand__3213E83FED0BF9C4" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="DOT_CandidatAppartenance" row_count="1" spec="" >
<column name="Id" type="int" jt="4" mandatory="y" >
<identity><![CDATA[IDENTITY]]></identity>
</column>
<column name="CandidatId" type="int" jt="4" mandatory="y" />
<column name="AppartenanceId" type="int" jt="4" mandatory="y" />
<column name="Valeur" type="bit" jt="-7" mandatory="y" />
<index name="pk_DOT_CandidatAppartenance" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="Id" options=" asc" />
</index>
<fk name="fk_DOT_CandidatAppartenance_DOT_Appartenance" to_schema="master.dbo" to_table="DOT_E_Appartenance" options="" >
<fk_column name="AppartenanceId" pk="id" />
</fk>
<fk name="fk_DOT_CandidatAppartenance_DOT_Candidat" to_schema="master.dbo" to_table="DOT_Candidat" options="" >
<fk_column name="CandidatId" pk="id" />
</fk>
</table>
<table name="DOT_E_Appartenance" row_count="2" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<index name="PK__DOT_E_Ap__3213E83FA38A4116" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="Employee" row_count="100" spec="" >
<column name="EmployeeID" type="int" jt="4" mandatory="y" />
<column name="Name" type="nvarchar" length="100" jt="12" mandatory="y" />
<column name="Position" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Department" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Address" type="nvarchar" length="1024" jt="12" mandatory="y" />
<column name="AnnualSalary" type="decimal" length="10" decimal="2" jt="3" mandatory="y" />
<column name="ValidFrom" type="datetime2" jt="92" mandatory="y" >
<identity><![CDATA[GENERATED ALWAYS AS ROW START]]></identity>
</column>
<column name="ValidTo" type="datetime2" jt="92" mandatory="y" >
<identity><![CDATA[GENERATED ALWAYS AS ROW END]]></identity>
</column>
<index name="PK__Employee__7AD04FF102DA7177" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="EmployeeID" options=" asc" />
</index>
<index name="TemporalPeriod" unique="INDEX2" >
<column name="ValidFrom" />
<column name="ValidTo" />
</index>
<options><![CDATA[WITH ( SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[EmployeeHistory]), )]]></options>
</table>
<table name="Employee2" row_count="0" spec="" >
<column name="EmployeeID" type="int" jt="4" mandatory="y" />
<column name="Name" type="nvarchar" length="100" jt="12" mandatory="y" />
<column name="Position" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Department" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Address" type="nvarchar" length="1024" jt="12" mandatory="y" />
<column name="AnnualSalary" type="decimal" length="10" decimal="2" jt="3" mandatory="y" />
<column name="ValidFrom" type="datetime2" jt="92" mandatory="y" >
<identity><![CDATA[GENERATED ALWAYS AS ROW START]]></identity>
</column>
<column name="ValidTo" type="datetime2" jt="92" mandatory="y" >
<identity><![CDATA[GENERATED ALWAYS AS ROW END]]></identity>
</column>
<index name="PK__Employee__7AD04FF195121D10" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="EmployeeID" options=" asc" />
</index>
<index name="TemporalPeriod" unique="INDEX2" >
<column name="ValidFrom" />
<column name="ValidTo" />
</index>
<options><![CDATA[WITH ( SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[EmployeeHistory2]), )]]></options>
</table>
<table name="EmployeeHistory" row_count="0" spec="" >
<column name="EmployeeID" type="int" jt="4" mandatory="y" />
<column name="Name" type="nvarchar" length="100" jt="12" mandatory="y" />
<column name="Position" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Department" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Address" type="nvarchar" length="1024" jt="12" mandatory="y" />
<column name="AnnualSalary" type="decimal" length="10" decimal="2" jt="3" mandatory="y" />
<column name="ValidFrom" type="datetime2" jt="92" mandatory="y" />
<column name="ValidTo" type="datetime2" jt="92" mandatory="y" />
<index name="ix_EmployeeHistory" unique="NORMAL" spec=" CLUSTERED" options="WITH (DATA_COMPRESSION = PAGE)" >
<column name="ValidTo" options=" asc" />
<column name="ValidFrom" options=" asc" />
</index>
</table>
<table name="EmployeeHistory2" row_count="0" spec="" >
<column name="EmployeeID" type="int" jt="4" mandatory="y" />
<column name="Name" type="nvarchar" length="100" jt="12" mandatory="y" />
<column name="Position" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Department" type="varchar" length="100" jt="12" mandatory="y" />
<column name="Address" type="nvarchar" length="1024" jt="12" mandatory="y" />
<column name="AnnualSalary" type="decimal" length="10" decimal="2" jt="3" mandatory="y" />
<column name="ValidFrom" type="datetime2" jt="92" mandatory="y" />
<column name="ValidTo" type="datetime2" jt="92" mandatory="y" />
<index name="ix_EmployeeHistory2" unique="NORMAL" spec=" CLUSTERED" options="WITH (DATA_COMPRESSION = PAGE)" >
<column name="ValidTo" options=" asc" />
<column name="ValidFrom" options=" asc" />
</index>
</table>
<table name="MSreplication_options" row_count="3" spec="" >
<column name="optname" type="sysname" jt="12" mandatory="y" />
<column name="value" type="bit" jt="-7" mandatory="y" />
<column name="major_version" type="int" jt="4" mandatory="y" />
<column name="minor_version" type="int" jt="4" mandatory="y" />
<column name="revision" type="int" jt="4" mandatory="y" />
<column name="install_failures" type="int" jt="4" mandatory="y" />
</table>
<table name="Users" row_count="0" spec="" >
<column name="UserId" type="int" jt="4" mandatory="y" />
<column name="UserName" type="nvarchar" length="200" jt="12" mandatory="y" />
<column name="AddressLinkId" type="int" jt="4" mandatory="y" />
<index name="PK_Users_UserId" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="UserId" options=" asc" />
</index>
</table>
<table name="contact" row_count="0" spec="" >
<column name="memberid" type="int" jt="4" />
<column name="name" type="varchar" length="100" jt="12" />
<index name="IX_Contact_MemberId" unique="UNIQUE_KEY" spec=" NONCLUSTERED" options=" WHERE ([MemberId] IS NOT NULL)" >
<column name="memberid" options=" asc" />
</index>
</table>
<table name="spt_fallback_db" row_count="0" spec="" >
<column name="xserver_name" type="varchar" length="30" jt="12" mandatory="y" />
<column name="xdttm_ins" type="datetime" jt="92" mandatory="y" />
<column name="xdttm_last_ins_upd" type="datetime" jt="92" mandatory="y" />
<column name="xfallback_dbid" type="smallint" jt="5" />
<column name="name" type="varchar" length="30" jt="12" mandatory="y" />
<column name="dbid" type="smallint" jt="5" mandatory="y" />
<column name="status" type="smallint" jt="5" mandatory="y" />
<column name="version" type="smallint" jt="5" mandatory="y" />
</table>
<table name="spt_fallback_dev" row_count="0" spec="" >
<column name="xserver_name" type="varchar" length="30" jt="12" mandatory="y" />
<column name="xdttm_ins" type="datetime" jt="92" mandatory="y" />
<column name="xdttm_last_ins_upd" type="datetime" jt="92" mandatory="y" />
<column name="xfallback_low" type="int" jt="4" />
<column name="xfallback_drive" type="char" length="2" jt="1" />
<column name="low" type="int" jt="4" mandatory="y" />
<column name="high" type="int" jt="4" mandatory="y" />
<column name="status" type="smallint" jt="5" mandatory="y" />
<column name="name" type="varchar" length="30" jt="12" mandatory="y" />
<column name="phyname" type="varchar" length="127" jt="12" mandatory="y" />
</table>
<table name="spt_fallback_usg" row_count="0" spec="" >
<column name="xserver_name" type="varchar" length="30" jt="12" mandatory="y" />
<column name="xdttm_ins" type="datetime" jt="92" mandatory="y" />
<column name="xdttm_last_ins_upd" type="datetime" jt="92" mandatory="y" />
<column name="xfallback_vstart" type="int" jt="4" />
<column name="dbid" type="smallint" jt="5" mandatory="y" />
<column name="segmap" type="int" jt="4" mandatory="y" />
<column name="lstart" type="int" jt="4" mandatory="y" />
<column name="sizepg" type="int" jt="4" mandatory="y" />
<column name="vstart" type="int" jt="4" mandatory="y" />
</table>
<table name="spt_monitor" row_count="1" spec="" >
<column name="lastrun" type="datetime" jt="92" mandatory="y" />
<column name="cpu_busy" type="int" jt="4" mandatory="y" />
<column name="io_busy" type="int" jt="4" mandatory="y" />
<column name="idle" type="int" jt="4" mandatory="y" />
<column name="pack_received" type="int" jt="4" mandatory="y" />
<column name="pack_sent" type="int" jt="4" mandatory="y" />
<column name="connections" type="int" jt="4" mandatory="y" />
<column name="pack_errors" type="int" jt="4" mandatory="y" />
<column name="total_read" type="int" jt="4" mandatory="y" />
<column name="total_write" type="int" jt="4" mandatory="y" />
<column name="total_errors" type="int" jt="4" mandatory="y" />
</table>
<table name="test" row_count="0" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<column name="firstName" type="nvarchar" length="100" jt="12" mandatory="y" />
</table>
<table name="test1" row_count="100" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<column name="name" type="varchar" length="100" jt="12" />
<column name="bb" type="bit" jt="-7" />
<index name="pk_test1" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
<fk name="fk_test1_test1_0" to_schema="master.dbo" to_table="test1_0" options="" >
<fk_column name="id" pk="id" />
<comment><![CDATA[ao deixar de ser compartilhado os dados são removidos da tabela e salvos no log. Identifies which boards the item can be shared, when it is no longer shared the data is deleted from the table and inserted in the log.]]></comment>
</fk>
</table>
<table name="test1_0" row_count="102" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<column name="name" type="varchar" length="100" jt="12" />
<index name="pk_test1_0" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="test22" row_count="0" spec="" >
<comment><![CDATA[ao deixar de ser compartilhado os dados são removidos da tabela e salvos no log.]]></comment>
<column name="id" type="int" jt="4" mandatory="y" >
<comment><![CDATA[ao deixar de ser compartilhado os dados são removidos da tabela e salvos no log. Identifies which boards the item can be shared, when it is no longer shared the data is deleted from the table and inserted in the log.]]></comment>
</column>
<index name="pk_test22" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="test_0" row_count="0" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<column name="firstname" type="varchar" length="100" jt="12" mandatory="y" >
<comment><![CDATA[some comment]]></comment>
</column>
<column name="lastname" type="varchar" length="100" jt="12" >
<comment><![CDATA[other comment2]]></comment>
</column>
<column name="dd" type="datetime2" jt="92" >
<comment><![CDATA[other comment]]></comment>
</column>
<index name="pk_test" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="test_bool" row_count="2" spec="" >
<column name="id" type="int" jt="4" mandatory="y" />
<column name="bool_field" type="bit" jt="-7" />
<column name="name" type="varchar" length="100" jt="12" />
<index name="pk_test_bool" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<table name="test_identity" row_count="0" spec="" >
<column name="id" type="int" jt="4" mandatory="y" >
<identity><![CDATA[IDENTITY]]></identity>
</column>
<index name="pk_test_identity" unique="PRIMARY_KEY" spec=" CLUSTERED" >
<column name="id" options=" asc" />
</index>
</table>
<view name="spt_values" >
<view_script><![CDATA[
create view spt_values as
select name collate database_default as name,
number,
type collate database_default as type,
low, high, status
from sys.spt_values
]]></view_script>
<column name="name" type="nvarchar" />
<column name="number" type="int" />
<column name="type" type="nchar" />
<column name="low" type="int" />
<column name="high" type="int" />
<column name="status" type="int" />
</view>
<procedure name="sp_GetDDL" id="Procedure-3a4" isSystem="false" params_known="y" >
<string><![CDATA[--#################################################################################################
-- Real World DBA Toolkit Version 2019-08-01 Lowell Izaguirre [email protected]
--#################################################################################################
-- USAGE: exec sp_GetDDL GMACT
-- or exec sp_GetDDL 'bob.example'
-- or exec sp_GetDDL '[schemaname].[tablename]'
-- or exec sp_GetDDL #temp
--#################################################################################################
-- copyright 2004-2018 by Lowell Izaguirre scripts*at*stormrage.com all rights reserved.
--developer utility function added by Lowell, used in SQL Server Management Studio
-- http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt
--Purpose: Script Any Table, Temp Table or Object(Procedure Function Synonym View Table Trigger)
--#################################################################################################
-- see the thread here for lots of details: http://www.sqlservercentral.com/Forums/Topic751783-566-7.aspx
-- You can use this however you like...this script is not rocket science, but it took a bit of work to create.
-- the only thing that I ask
-- is that if you adapt my procedure or make it better, to simply send me a copy of it,
-- so I can learn from the things you've enhanced.The feedback you give will be what makes
-- it worthwhile to me, and will be fed back to the SQL community.
-- add this to your toolbox of helpful scripts.
--#################################################################################################
--
-- V300 uses String concatination and sys.tables instead of a cursor
-- V301 enhanced 07/31/2009 to include extended properties definitions
-- V302 fixes an issue where the schema is created , ie 'bob', but no user named 'bob' owns the schema, so the table is not found
-- V303 fixes an issue where all rules are appearing, instead of jsut the rule related to a column
-- V304 testing whether vbCrLf is better than just CHAR(13), some formatting cleanup with GO statements
-- also fixed an issue with the conversion from syscolumns to sys.columns, max-length is only field we need, not [precision]
-- V305 user feedback helped me find that the type_name function should call user_type_id instead of system_type_id
-- also fixed issue where identity definition missing from numeric/decimal definition
-- V306 fixes the computed columns definition that got broken/removed somehow in V300
-- also formatting when decimal is not an identity
-- V307 fixes bug identified by David Griffiths-491597 from SSC where the @TABLE_ID
-- is reselected, but without it's schema , potentially selecting the wrong table
-- also fixed is the missing size definition for varbinary, also found by David Griffith
-- V308 abtracted all SQLs to use Table Alaises
-- added logic to script a temp table.
-- added warning about possibly not being marked as system object.
-- V309 added logic based on feedback from Vincent Wylenzek @SSC to return the definition from sys.sql_modules for
-- any object like procedure/view/function/trigger, and not just a table.
-- note previously, if you pointed sp_GetDDL at a view, it returned the view definition as a table...
-- now it will return the view definition instead.
-- V309a returns multi row recordset, one line per record
-- V310a fixed the commented out code related to collation identified by moadh.bs @SSC
-- changed the DEFAULT definitions to not include the default name.
-- V310b Added PERSISTED to calculated columns where applicable
-- V310b fixed COLLATE statement for temp tables
-- V310c fixed NVARCHAR size misreported as doubled.
-- V311 fixed issue where indexes did not identify if the column was ASC or DESC found by nikus @ SSC
-- V311a fixed issue where indexes did not identify if the index was CLUSTERED or NONCLUSTERED found by nikus @ SSC 02/22/2013
-- V312 got rid of all upper casing, and allowing all scripts to generate the exact object names in cases of case sensitive databases.
-- now using the case sensitive name of the table passed: so of you did 'exec sp_GetDDL invoicedocs , it might return the script for InvoiceDocs, as that is how it is spelled in sys.objects.
-- added if exists(drop table/procedure/function) statement to the scripting automatically.
-- toggled the commented out code to list any default constraints by name, hopefully to be more accurate..
-- formatting of index statements to be multi line for better readability
--V314 03/30/2015
-- did i mention this scripts out temp tables too? sp_GetDDL #tmp
-- scripts any object:table,#temptable procedure, function, view or trigger
-- added ability to script synonyms
-- moved logic for REAL datatype to fix error when scripting real columns
-- added OmaCoders suggestion to script column extended properties as well.
-- added matt_slack suggestion to script schemaname as part of index portion of script.
-- minor script cleanup to use QUOTENAME insead of concatenating square brackets.
-- changed compatibility to 2008 and above only, now filtered idnexes with WHERE statmeents script correctly
-- foreign key tables and columns in script now quotenamed to account for spaces in names; previously an error for Applciation ID instead of [Application ID]
--V315 Fixes Aliases and column names that prevented Case Sensitive collations from working.
-- Adds code if the procedure scripted is a system object
-- index scripts featuring filtered indexes is now included
-- index scripts now include filegroup name and compression settings
-- foreign key casecade delete/update settings now included as identified by Alberto aserio@SSC)
-- Fixes related to scripting extended events as identified by Alberto aserio@SSC)
--V316 Fixes Identified 07/27/2016 by mlm( m.martinelli@SSC)
-- Added logic resolving error when custom data type are defined using name greather than 16 char.
-- Added handling for data types: binary, datetime2, datetimeoffset, time
-- Added Set Based logic for Handling Fixed FOREIGN KEYS handling when one foreign key is define on more then one field
-- Added SPARSE column property
--V317 Fixes Identified 03/30/2017 by Lowell
-- Scripting of Foreign key column(s) are now quotenamed
-- Scripting column store indexes was broken, now fixed for column store indexes
--V318 Fixes Identified 02/14/2018 by Lowell
-- Scripting of with collation added/required for scripting SharePoint/ReportServer , or databases with non standard collations
-- Scripting enhanced to definitively handle case sensitive collations as well.
--V319 Adding logic for Temporal Tables, to grab their auto nistory tables
-- first attempt for partitioned tables, to get the columns correctly on the partition scheme
-- DROP PROCEDURE [dbo].[sp_GetDDL]
--#############################################################################
--if you are going to put this in MASTER, and want it to be able to query
--each database's sys.indexes, you MUST mark it as a system procedure:
--EXECUTE sp_ms_marksystemobject 'sp_GetDDL'
--#############################################################################
-- REMOVE TWO LINES WHERE IS THE TEXT 'FROM master.sys.objects'
-- REPLACE HEADER 'CREATE OR ALTER PROCEDURE [dbo].[sp_GetDDL]'
CREATE PROCEDURE [dbo].[sp_GetDDL]
@TBL VARCHAR(255)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TBLNAME VARCHAR(200),
@SCHEMANAME VARCHAR(255),
@STRINGLEN INT,
@TABLE_ID INT,
@FINALSQL VARCHAR(MAX),
@CONSTRAINTSQLS VARCHAR(MAX),
@CHECKCONSTSQLS VARCHAR(MAX),
@RULESCONSTSQLS VARCHAR(MAX),
@FKSQLS VARCHAR(MAX),
@TRIGGERSTATEMENT VARCHAR(MAX),
@EXTENDEDPROPERTIES VARCHAR(MAX),
@INDEXSQLS VARCHAR(MAX),
@MARKSYSTEMOBJECT VARCHAR(MAX),
@vbCrLf CHAR(2),
@ISSYSTEMOBJECT INT,
@PROCNAME VARCHAR(256),
@input VARCHAR(MAX),
@ObjectTypeFound VARCHAR(255),
@ObjectDataTypeLen INT,
--V3.20 additions
@WithStatement VARCHAR(MAX),
@FileGroupStatement VARCHAR(MAX),
@PartitioningStatement VARCHAR(MAX),
@TemporalStatement VARCHAR(MAX);
--##############################################################################
-- INITIALIZE
--##############################################################################
SET @input = '';
--new code: determine whether this proc is marked as a system proc with sp_ms_marksystemobject,
--which flips the is_ms_shipped bit in sys.objects
SELECT @ISSYSTEMOBJECT = ISNULL([is_ms_shipped],0),@PROCNAME = ISNULL([name],'sp_GetDDL') FROM [sys].[objects] WHERE [object_id] = @@PROCID;
IF @ISSYSTEMOBJECT IS NULL
SET @ISSYSTEMOBJECT = 0;
IF @PROCNAME IS NULL
SET @PROCNAME = 'sp_GetDDL';
--SET @TBL = '[DBO].[WHATEVER1]'
--does the tablename contain a schema?
SET @vbCrLf = CHAR(10);
SELECT @SCHEMANAME = ISNULL(PARSENAME(@TBL,2),'dbo') ,
@TBLNAME = PARSENAME(@TBL,1);
SELECT
@TBLNAME = [objz].[name],
@TABLE_ID = [objz].[object_id]
FROM [sys].[objects] AS [objz]
WHERE [objz].[type] IN ('S','U')
AND [objz].[name] <> 'dtproperties'
AND [objz].[name] = @TBLNAME
AND [objz].[schema_id] = SCHEMA_ID(@SCHEMANAME) ;
SELECT @ObjectDataTypeLen = MAX(LEN([name])) FROM [sys].[types];
--##############################################################################
-- Check If TEMP TableName is Valid
--##############################################################################
IF LEFT(@TBLNAME,1) = '#' COLLATE SQL_Latin1_General_CP1_CI_AS
BEGIN
PRINT '--TEMP TABLE ' + QUOTENAME(@TBLNAME) + ' FOUND';
IF OBJECT_ID('tempdb..' + QUOTENAME(@TBLNAME)) IS NOT NULL
BEGIN
PRINT '--GOIN TO TEMP PROCESSING';
GOTO TEMPPROCESS;
END;
END;
ELSE
BEGIN
PRINT '--Non-Temp Table, ' + QUOTENAME(@TBLNAME) + ' continue Processing';
END;
--##############################################################################
-- Check If TableName is Valid
--##############################################################################
IF ISNULL(@TABLE_ID,0) = 0
BEGIN
--V309 code: see if it is an object and not a table.
SELECT
@TBLNAME = [objz].[name],
@TABLE_ID = [objz].[object_id],
@ObjectTypeFound = [objz].[type_desc]
FROM [sys].[objects] AS [objz]
--WHERE [type_desc] IN('SQL_STORED_PROCEDURE','VIEW','SQL_TRIGGER','AGGREGATE_FUNCTION','SQL_INLINE_TABLE_VALUED_FUNCTION','SQL_TABLE_VALUED_FUNCTION','SQL_SCALAR_FUNCTION','SYNONYMN')
WHERE [objz].[type] IN ('P','V','TR','AF','IF','FN','TF','SN')
AND [objz].[name] <> 'dtproperties'
AND [objz].[name] = @TBLNAME
AND [objz].[schema_id] = SCHEMA_ID(@SCHEMANAME) ;
IF ISNULL(@TABLE_ID,0) <> 0
BEGIN
--adding a drop statement.
--adding a sp_ms_marksystemobject if needed
SELECT @MARKSYSTEMOBJECT = CASE
WHEN [objz].[is_ms_shipped] = 1
THEN '
GO
--#################################################################################################
--Mark as a system object
EXECUTE sp_ms_marksystemobject ''' + QUOTENAME(@SCHEMANAME) +'.' + QUOTENAME(@TBLNAME) + '''
--#################################################################################################
'
ELSE '
GO
'
END
FROM [sys].[objects] AS [objz]
WHERE [objz].[object_id] = @TABLE_ID;
--adding a drop statement.
IF @ObjectTypeFound = 'SYNONYM' COLLATE SQL_Latin1_General_CP1_CI_AS
BEGIN
SELECT @FINALSQL =
'IF EXISTS(SELECT * FROM sys.synonyms WHERE name = '''
+ [name]
+ ''''
+ ' AND base_object_name <> ''' + [base_object_name] + ''')'
+ @vbCrLf
+ ' DROP SYNONYM ' + QUOTENAME([name]) + ''
+ @vbCrLf
+'GO'
+ @vbCrLf
+'IF NOT EXISTS(SELECT * FROM sys.synonyms WHERE name = '''
+ [name]
+ ''')'
+ @vbCrLf
+ 'CREATE SYNONYM ' + QUOTENAME([name]) + ' FOR ' + [base_object_name] +';'
FROM [sys].[synonyms]
WHERE [name] = @TBLNAME
AND [schema_id] = SCHEMA_ID(@SCHEMANAME);
END;
ELSE
BEGIN
SELECT @FINALSQL =
'IF OBJECT_ID(''' + QUOTENAME(@SCHEMANAME) + '.' + QUOTENAME(@TBLNAME) + ''') IS NOT NULL ' + @vbCrLf
+ 'DROP ' + CASE
WHEN [objz].[type] IN ('P')
THEN ' PROCEDURE '
WHEN [objz].[type] IN ('V')
THEN ' VIEW '
WHEN [objz].[type] IN ('TR')
THEN ' TRIGGER '
ELSE ' FUNCTION '
END
+ QUOTENAME(@SCHEMANAME) + '.' + QUOTENAME(@TBLNAME) + ' ' + @vbCrLf + 'GO' + @vbCrLf
+ [def].[definition] + @MARKSYSTEMOBJECT
FROM [sys].[objects] AS [objz]
INNER JOIN [sys].[sql_modules] AS [def]
ON [objz].[object_id] = [def].[object_id]
WHERE [objz].[type] IN ('P','V','TR','AF','IF','FN','TF')
AND [objz].[name] <> 'dtproperties'
AND [objz].[name] = @TBLNAME
AND [objz].[schema_id] = SCHEMA_ID(@SCHEMANAME) ;
END;
SET @input = @FINALSQL
--ten years worth of days from todays date:
;WITH [E01]([N]) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1), -- 10 or 10E01 rows
[E02]([N]) AS (SELECT 1 FROM [E01] AS [a], [E01] AS [b]), -- 100 or 10E02 rows
[E04]([N]) AS (SELECT 1 FROM [E02] AS [a], [E02] AS [b]), -- 10,000 or 10E04 rows
[E08]([N]) AS (SELECT 1 FROM [E04] AS [a], [E04] AS [b]), --100,000,000 or 10E08 rows
--E16(N) AS (SELECT 1 FROM E08 a, E08 b), --10E16 or more rows than you'll EVER need,
[Tally]([N]) AS (SELECT ROW_NUMBER() OVER (ORDER BY [E08].[N]) FROM [E08]),
[ItemSplit](
[ItemOrder],
[Item]
) AS (
SELECT [Tally].[N],
SUBSTRING(@vbCrLf + @input + @vbCrLf,[Tally].[N] + DATALENGTH(@vbCrLf),CHARINDEX(@vbCrLf,@vbCrLf + @input + @vbCrLf,[Tally].[N] + DATALENGTH(@vbCrLf)) - [Tally].[N] - DATALENGTH(@vbCrLf))
FROM [Tally]
WHERE [Tally].[N] < DATALENGTH(@vbCrLf + @input)
--WHERE N < DATALENGTH(@vbCrLf + @input) -- REMOVED added @vbCrLf
AND SUBSTRING(@vbCrLf + @input + @vbCrLf,[Tally].[N],DATALENGTH(@vbCrLf)) = @vbCrLf --Notice how we find the delimiter
)
SELECT
--row_number() over (order by ItemOrder) as ItemID,
[ItemSplit].[Item]
FROM [ItemSplit];
RETURN 0;
END;
ELSE
BEGIN
SET @FINALSQL = 'Object ' + QUOTENAME(@SCHEMANAME) + '.' + QUOTENAME(@TBLNAME) + ' does not exist in Database ' + QUOTENAME(DB_NAME()) + ' '
+ CASE
WHEN @ISSYSTEMOBJECT = 0 THEN @vbCrLf + ' (also note that ' + @PROCNAME + ' is not marked as a system proc and cross db access to sys.tables will fail.)'
ELSE ''
END;
IF LEFT(@TBLNAME,1) = '#'
SET @FINALSQL = @FINALSQL + ' OR in The tempdb database.';
SELECT @FINALSQL AS [Item];
RETURN 0;
END;
END;
--##############################################################################
-- Valid Table, Continue Processing
--##############################################################################
--Is this a SYSTEM versioned TABLE?
SELECT @FINALSQL =
CASE
WHEN [tabz].[history_table_id] IS NULL
THEN ''
ELSE 'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[object_id]) ) + '.' + QUOTENAME(OBJECT_NAME([tabz].[object_id])) + ' SET (SYSTEM_VERSIONING = OFF);' + @vbCrLf
+ 'IF OBJECT_ID(''' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[history_table_id]) ) + '.' + QUOTENAME(OBJECT_NAME([tabz].[history_table_id])) + ''') IS NOT NULL ' + @vbCrLf
+ 'DROP TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[history_table_id])) + '.' + QUOTENAME(OBJECT_NAME([tabz].[history_table_id])) + ' ' + @vbCrLf + 'GO' + @vbCrLf
END
+ 'IF OBJECT_ID(''' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[object_id]) ) + '.' + QUOTENAME(OBJECT_NAME([tabz].[object_id])) + ''') IS NOT NULL ' + @vbCrLf
+ 'DROP TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[object_id])) + '.' + QUOTENAME(OBJECT_NAME([tabz].[object_id])) + ' ' + @vbCrLf + 'GO' + @vbCrLf
+ 'CREATE ' + ( CASE WHEN tabz.is_external = 1 THEN 'EXTERNAL ' ELSE '' END ) + 'TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME([tabz].[object_id])) + '.' + QUOTENAME(OBJECT_NAME([tabz].[object_id])) + ' ( '
FROM [sys].[tables] [tabz] WHERE [tabz].[object_id] = @TABLE_ID
PRINT @FINALSQL
--removed invalid code here which potentially selected wrong table--thanks David Grifiths @SSC!
SELECT
@STRINGLEN = MAX(LEN([colz].[name])) + 1
FROM [sys].[objects] AS [objz]
INNER JOIN [sys].[columns] AS [colz]
ON [objz].[object_id] = [colz].[object_id]
AND [objz].[object_id] = @TABLE_ID;
--##############################################################################
--Get the columns, their definitions and defaults.
--##############################################################################
SELECT
@FINALSQL = @FINALSQL
+ CASE
WHEN [colz].[is_computed] = 1
THEN @vbCrLf
+ QUOTENAME([colz].[name])
+ ' '
+ SPACE(@STRINGLEN - LEN([colz].[name]))
+ 'AS ' + ISNULL([CALC].[definition],'')
+ CASE
WHEN [CALC].[is_persisted] = 1
THEN ' PERSISTED'
ELSE ''
END
ELSE @vbCrLf
+ QUOTENAME([colz].[name])
+ ' '
+ SPACE(@STRINGLEN - LEN([colz].[name]))
+ UPPER(TYPE_NAME([colz].[user_type_id]))
+ CASE
-- data types with precision and scale IE DECIMAL(18,3), NUMERIC(10,2)
WHEN TYPE_NAME([colz].[user_type_id]) IN ('decimal','numeric')
THEN '('
+ CONVERT(VARCHAR,[colz].[precision])
+ ','
+ CONVERT(VARCHAR,[colz].[scale])
+ ') '
+ SPACE(6 - LEN(CONVERT(VARCHAR,[colz].[precision])
+ ','
+ CONVERT(VARCHAR,[colz].[scale])))
+ SPACE(7)
+ SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
+ CASE
WHEN COLUMNPROPERTY ( @TABLE_ID , [colz].[name] , 'IsIdentity' ) = 0
THEN ''
WHEN ISNULL(IDENT_SEED(@TBLNAME),1) = 1 AND ISNULL(IDENT_INCR(@TBLNAME),1) = 1
THEN ' IDENTITY'
ELSE ' IDENTITY('
+ CONVERT(VARCHAR,ISNULL(IDENT_SEED(@TBLNAME),1) )
+ ','
+ CONVERT(VARCHAR,ISNULL(IDENT_INCR(@TBLNAME),1) )
+ ')'
END
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
-- data types with scale IE datetime2(7),TIME(7)
WHEN TYPE_NAME([colz].[user_type_id]) IN ('datetime2','datetimeoffset','time')
THEN CASE
WHEN [colz].[scale] < 7 THEN
'('
+ CONVERT(VARCHAR,[colz].[scale])
+ ') '
ELSE
' '
END
+ SPACE(4)
+ SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
+ ' '
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE [colz].[generated_always_type]
WHEN 0 THEN ''
WHEN 1 THEN ' GENERATED ALWAYS AS ROW START'
WHEN 2 THEN ' GENERATED ALWAYS AS ROW END'
ELSE ''
END
+ CASE WHEN [colz].[is_hidden] = 1 THEN ' HIDDEN' ELSE '' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
--data types with no/precision/scale,IE FLOAT
WHEN TYPE_NAME([colz].[user_type_id]) IN ('float') --,'real')
THEN
--addition: if 53, no need to specifically say (53), otherwise display it
CASE
WHEN [colz].[precision] = 53
THEN SPACE(11 - LEN(CONVERT(VARCHAR,[colz].[precision])))
+ SPACE(7)
+ SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
ELSE '('
+ CONVERT(VARCHAR,[colz].[precision])
+ ') '
+ SPACE(6 - LEN(CONVERT(VARCHAR,[colz].[precision])))
+ SPACE(7) + SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
END
--data type with max_length ie CHAR (44), VARCHAR(40), BINARY(5000),
--##############################################################################
-- COLLATE STATEMENTS
-- personally i do not like collation statements,
-- but included here to make it easy on those who do
--##############################################################################
WHEN TYPE_NAME([colz].[user_type_id]) IN ('char','varchar','binary','varbinary')
THEN CASE
WHEN [colz].[max_length] = -1
THEN '(max)'
+ SPACE(6 - LEN(CONVERT(VARCHAR,[colz].[max_length])))
+ SPACE(7) + SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
----collate to comment out when not desired
--+ CASE
-- WHEN COLS.collation_name IS NULL
-- THEN ''
-- ELSE ' COLLATE ' + COLS.collation_name
-- END
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
ELSE '('
+ CONVERT(VARCHAR,[colz].[max_length])
+ ') '
+ SPACE(6 - LEN(CONVERT(VARCHAR,[colz].[max_length])))
+ SPACE(7) + SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
----collate to comment out when not desired
--+ CASE
-- WHEN COLS.collation_name IS NULL
-- THEN ''
-- ELSE ' COLLATE ' + COLS.collation_name
-- END
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
END
--data type with max_length ( BUT DOUBLED) ie NCHAR(33), NVARCHAR(40)
WHEN TYPE_NAME([colz].[user_type_id]) IN ('nchar','nvarchar')
THEN CASE
WHEN [colz].[max_length] = -1
THEN '(max)'
+ SPACE(5 - LEN(CONVERT(VARCHAR,([colz].[max_length] / 2))))
+ SPACE(7)
+ SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
----collate to comment out when not desired
--+ CASE
-- WHEN COLS.collation_name IS NULL
-- THEN ''
-- ELSE ' COLLATE ' + COLS.collation_name
-- END
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
ELSE '('
+ CONVERT(VARCHAR,([colz].[max_length] / 2))
+ ') '
+ SPACE(6 - LEN(CONVERT(VARCHAR,([colz].[max_length] / 2))))
+ SPACE(7)
+ SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
----collate to comment out when not desired
--+ CASE
-- WHEN COLS.collation_name IS NULL
-- THEN ''
-- ELSE ' COLLATE ' + COLS.collation_name
-- END
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
END
WHEN TYPE_NAME([colz].[user_type_id]) IN ('datetime','money','text','image','real')
THEN SPACE(18 - LEN(TYPE_NAME([colz].[user_type_id])))
+ ' '
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
-- other data type IE INT, DATETIME, MONEY, CUSTOM DATA TYPE,...
ELSE SPACE(@ObjectDataTypeLen - LEN(TYPE_NAME([colz].[user_type_id])))
+ CASE
WHEN COLUMNPROPERTY ( @TABLE_ID , [colz].[name] , 'IsIdentity' ) = 0
THEN ' '
WHEN ISNULL(IDENT_SEED(@TBLNAME),1) = 1 AND ISNULL(IDENT_INCR(@TBLNAME),1) = 1
THEN ' IDENTITY'
ELSE ' IDENTITY('
+ CONVERT(VARCHAR,ISNULL(IDENT_SEED(@TBLNAME),1) )
+ ','
+ CONVERT(VARCHAR,ISNULL(IDENT_INCR(@TBLNAME),1) )
+ ')'
END
+ SPACE(2)
+ CASE WHEN [colz].[is_sparse] = 1 THEN ' sparse' ELSE ' ' END
+ CASE
WHEN [colz].[is_nullable] = 0
THEN ' NOT NULL'
ELSE ' NULL'
END
END
+ CASE
WHEN [colz].[default_object_id] = 0
THEN ''
--ELSE ' DEFAULT ' + ISNULL(def.[definition] ,'')
--optional section in case NAMED default constraints are needed:
ELSE ' CONSTRAINT ' + QUOTENAME([DEF].[name]) + ' DEFAULT ' + ISNULL([DEF].[definition] ,'')
--i thought it needed to be handled differently! NOT!
END --CASE cdefault
END --iscomputed
+ ','
FROM [sys].[columns] AS [colz]
LEFT OUTER JOIN [sys].[default_constraints] AS [DEF]
ON [colz].[default_object_id] = [DEF].[object_id]
LEFT OUTER JOIN [sys].[computed_columns] AS [CALC]
ON [colz].[object_id] = [CALC].[object_id]
AND [colz].[column_id] = [CALC].[column_id]
WHERE [colz].[object_id]=@TABLE_ID
ORDER BY [colz].[column_id];
--##############################################################################
--used for formatting the rest of the constraints:
--##############################################################################
SELECT
@STRINGLEN = MAX(LEN([objz].[name])) + 1
FROM [sys].[objects] AS [objz];
--##############################################################################
--PK/Unique Constraints and Indexes, using the 2005/08 INCLUDE syntax
--##############################################################################
DECLARE @Results TABLE (
[SCHEMA_ID] INT,
[SCHEMA_NAME] VARCHAR(255),
[OBJECT_ID] INT,
[OBJECT_NAME] VARCHAR(255),
[index_id] INT,
[index_name] VARCHAR(255),
[ROWS] BIGINT,
[SizeMB] DECIMAL(19,3),
[IndexDepth] INT,
[TYPE] INT,
[type_desc] VARCHAR(30),
[fill_factor] INT,
[is_unique] INT,
[is_primary_key] INT ,
[is_unique_constraint] INT,
[index_columns_key] VARCHAR(MAX),
[index_columns_include] VARCHAR(MAX),
[has_filter] BIT ,
[filter_definition] VARCHAR(MAX),
[currentFilegroupName] VARCHAR(128),
[CurrentCompression] VARCHAR(128));
INSERT INTO @Results
SELECT
[SCH].[schema_id], [SCH].[name] AS [SCHEMA_NAME],
[objz].[object_id], [objz].[name] AS [OBJECT_NAME],
[IDX].[index_id], ISNULL([IDX].[name], '---') AS [index_name],
[partitions].[ROWS], [partitions].[SizeMB], INDEXPROPERTY([objz].[object_id], [IDX].[name], 'IndexDepth') AS [IndexDepth],
[IDX].[type], [IDX].[type_desc], [IDX].[fill_factor],
[IDX].[is_unique], [IDX].[is_primary_key], [IDX].[is_unique_constraint],
ISNULL([Index_Columns].[index_columns_key], '---') AS [index_columns_key],
ISNULL([Index_Columns].[index_columns_include], '---') AS [index_columns_include],
[IDX].[has_filter],
[IDX].[filter_definition],
[filz].[name],
ISNULL([p].[data_compression_desc],'')
FROM [sys].[objects] AS [objz]
INNER JOIN [sys].[schemas] AS [SCH] ON [objz].[schema_id]=[SCH].[schema_id]
INNER JOIN [sys].[indexes] AS [IDX] ON [objz].[object_id]=[IDX].[object_id]
INNER JOIN [sys].[filegroups] AS [filz] ON [IDX].[data_space_id] = [filz].[data_space_id]
INNER JOIN [sys].[partitions] AS [p] ON [IDX].[object_id] = [p].[object_id] AND [IDX].[index_id] = [p].[index_id]
INNER JOIN (
SELECT
[statz].[object_id], [statz].[index_id], SUM([statz].[row_count]) AS [ROWS],
CONVERT(NUMERIC(19,3), CONVERT(NUMERIC(19,3), SUM([statz].[in_row_reserved_page_count]+[statz].[lob_reserved_page_count]+[statz].[row_overflow_reserved_page_count]))/CONVERT(NUMERIC(19,3), 128)) AS [SizeMB]
FROM [sys].[dm_db_partition_stats] AS [statz]
GROUP BY [statz].[object_id], [statz].[index_id]
) AS [partitions]
ON [IDX].[object_id]=[partitions].[object_id]
AND [IDX].[index_id]=[partitions].[index_id]
CROSS APPLY (
SELECT
LEFT([Index_Columns].[index_columns_key], LEN([Index_Columns].[index_columns_key])-1) AS [index_columns_key],
LEFT([Index_Columns].[index_columns_include], LEN([Index_Columns].[index_columns_include])-1) AS [index_columns_include]
FROM
(
SELECT
(
SELECT QUOTENAME([colz].[name]) + CASE WHEN [IXCOLS].[is_descending_key] = 0 THEN ' asc' ELSE ' desc' END + ',' + ' '
FROM [sys].[index_columns] AS [IXCOLS]
INNER JOIN [sys].[columns] AS [colz]
ON [IXCOLS].[column_id] = [colz].[column_id]
AND [IXCOLS].[object_id] = [colz].[object_id]
WHERE [IXCOLS].[is_included_column] = 0
AND [IDX].[object_id] = [IXCOLS].[object_id]
AND [IDX].[index_id] = [IXCOLS].[index_id]
ORDER BY [IXCOLS].[key_ordinal]
FOR XML PATH('')
) AS [index_columns_key],
(
SELECT QUOTENAME([colz].[name]) + ',' + ' '
FROM [sys].[index_columns] AS [IXCOLS]
INNER JOIN [sys].[columns] AS [colz]
ON [IXCOLS].[column_id] = [colz].[column_id]
AND [IXCOLS].[object_id] = [colz].[object_id]
WHERE [IXCOLS].[is_included_column] = 1
AND [IDX].[object_id] = [IXCOLS].[object_id]
AND [IDX].[index_id] = [IXCOLS].[index_id]
ORDER BY [IXCOLS].[index_column_id]
FOR XML PATH('')
) AS [index_columns_include]
) AS [Index_Columns]
) AS [Index_Columns]
WHERE [SCH].[name] LIKE CASE
WHEN @SCHEMANAME = '' COLLATE SQL_Latin1_General_CP1_CI_AS
THEN [SCH].[name]
ELSE @SCHEMANAME
END
AND [objz].[name] LIKE CASE
WHEN @TBLNAME = '' COLLATE SQL_Latin1_General_CP1_CI_AS
THEN [objz].[name]
ELSE @TBLNAME
END
ORDER BY
[SCH].[name],
[objz].[name],
[IDX].[name];
--@Results table has both PK,s Uniques and indexes in thme...pull them out for adding to funal results:
SET @CONSTRAINTSQLS = '';
SET @INDEXSQLS = '';
SET @TemporalStatement = '';
SET @WithStatement = '';
--##############################################################################
-- Temporal tables
--##############################################################################
SELECT @TemporalStatement = ISNULL(@vbCrLf + 'PERIOD FOR SYSTEM_TIME ('
+ MAX(CASE WHEN [colz].[generated_always_type] = 1 THEN [colz].[name] ELSE '' END)
+','
+ MAX(CASE WHEN [colz].[generated_always_type] = 2 THEN [colz].[name] ELSE '' END)
+'),','') ,
@WithStatement = ISNULL(' SYSTEM_VERSIONING = ON (HISTORY_TABLE=' + QUOTENAME(OBJECT_SCHEMA_NAME([objz].[history_table_id])) + '.' + QUOTENAME(OBJECT_NAME([objz].[history_table_id])) + '),' ,'')
FROM [sys].[tables] [objz]
INNER JOIN [sys].[columns] [colz]
ON [objz].[object_id] = [colz].[object_id]
WHERE [colz].[object_id] = @TABLE_ID
AND [colz].[generated_always_type] > 0
GROUP BY [colz].[object_id],[objz].[history_table_id];
--##############################################################################
-- External tables
--##############################################################################
SELECT @WithStatement = @WithStatement + CASE WHEN [etabz].[location] IS NOT NULL THEN ' LOCATION = ' + [etabz].[location] + ',' END
+ CASE WHEN [etabz].[data_source_id] IS NOT NULL THEN ' DATA_SOURCE = ' + [eds].[name] + ',' END
+ CASE WHEN [etabz].[file_format_id] IS NOT NULL THEN ' FILE_FORMAT = ' + [efs].[name] + ',' END
+ CASE WHEN [etabz].[reject_type] IS NOT NULL THEN ' REJECT_TYPE = ' + [etabz].[reject_type] + ',' END
+ CASE WHEN [etabz].[reject_value] IS NOT NULL THEN ' REJECT_VALUE = ' + [etabz].[reject_value] + ',' END
+ CASE WHEN [etabz].[reject_sample_value] IS NOT NULL THEN ' REJECT_SAMPLE_VALUE = ' + [etabz].[reject_sample_value] + ',' END
+ ' '
FROM [sys].[external_tables] [etabz]
LEFT JOIN [sys].[external_data_sources] [eds] ON [eds].[data_source_id] = [etabz].[data_source_id]
LEFT JOIN [sys].[external_file_formats] [efs] ON [efs].[file_format_id] = [etabz].[file_format_id]
WHERE [etabz].[schema_id] = SCHEMA_ID(@SCHEMANAME) AND [etabz].[name] = @TBLNAME;
--##############################################################################
-- memory optimized
--##############################################################################
SELECT @WithStatement = @WithStatement + ISNULL('MEMORY_OPTIMIZED=ON, DURABILITY=' + [objz].[durability_desc] + ',','')
FROM [sys].[tables] [objz]
WHERE [objz].[is_memory_optimized] =1
AND [objz].[object_id] = @TABLE_ID
--##############################################################################
--constraints
--column store indexes are different: the "include" columns for normal indexes as scripted above are the columnstores indexed columns
--add a CASE for that situation.
--##############################################################################
SELECT @CONSTRAINTSQLS = @CONSTRAINTSQLS
+ CASE
WHEN [is_primary_key] = 1 OR [is_unique] = 1
THEN @vbCrLf
+ 'CONSTRAINT ' COLLATE SQL_Latin1_General_CP1_CI_AS + QUOTENAME([index_name]) + ' '
+ CASE
WHEN [is_primary_key] = 1
THEN ' PRIMARY KEY '
ELSE CASE
WHEN [is_unique] = 1
THEN ' UNIQUE '
ELSE ''
END
END
+ [type_desc]
+ CASE
WHEN [type_desc]='NONCLUSTERED'
THEN ''
ELSE ' '
END
+ ' (' + [index_columns_key] + ')'
+ CASE
WHEN [index_columns_include] <> '---'
THEN ' INCLUDE (' + [index_columns_include] + ')'
ELSE ''
END
+ CASE
WHEN [has_filter] = 1
THEN ' ' + [filter_definition]
ELSE ' '
END
+ CASE WHEN [fill_factor] <> 0 OR [CurrentCompression] <> 'NONE'
THEN ' WITH (' + CASE
WHEN [fill_factor] <> 0
THEN 'FILLFACTOR = ' + CONVERT(VARCHAR(30),[fill_factor])
ELSE ''
END
+ CASE
WHEN [fill_factor] <> 0 AND [CurrentCompression] <> 'NONE' THEN ',DATA_COMPRESSION = ' + [CurrentCompression] + ' '
WHEN [fill_factor] <> 0 AND [CurrentCompression] = 'NONE' THEN ''
WHEN [fill_factor] = 0 AND [CurrentCompression] <> 'NONE' THEN 'DATA_COMPRESSION = ' + [CurrentCompression] + ' '
ELSE ''
END
+ ')'
ELSE ''
END
ELSE ''
END + ','
FROM @Results
WHERE [type_desc] != 'HEAP'
AND [is_primary_key] = 1
OR [is_unique] = 1