· 5 years ago · Apr 20, 2020, 08:24 AM
1use catalog;
2go
3
4drop table if exists Foo;
5go
6
7-- 1.1 --
8
9create table Foo
10(
11 Field1 int not null,
12 Field2 varchar(10)
13);
14go
15
16-- 1.2 --
17-- Nein die Tabelle hat keinen Index
18
19-- 1.3 --
20
21alter table Foo
22 add primary key(Field1)
23;
24go
25
26-- Ja es gibt einen Index, "PK__Foo__36060C5E1839FA4D"
27
28-- 1.4 --
29
30alter table Foo
31 add unique(Field2)
32;
33go
34
35-- Nein, es gibt keinen weiteren Index
36
37-- 1.5 --
38drop table Foo;
39go
40
41create table Foo
42(
43 Field1 int not null,
44 Field2 varchar(10)
45);
46go
47
48-- 2.1 --
49
50create unique nonclustered index IX_Foo_Field2_Nonclustered
51 on Foo(Field2);
52go
53
54-- 2.2 --
55
56insert into Foo
57 (Field1, Field2)
58values
59 ( 10, 'Hello!')
60, ( 10, 'Bye!')
61, ( 50, 'Hello!')
62;
63go
64
65-- 2.3 --
66-- Weil 'Hello!' zweimal vorkommt, was bei unique nicht erlaubt ist.
67
68-- 2.4 --
69
70exec sp_spaceused Foo;
71go
72
73-- Data: 8kB, index_size: 24 kB
74
75-- 2.5 --
76
77drop index IX_Foo_Field2_Nonclustered
78 on Foo
79;
80go
81
82-- 3.1 --
83
84create clustered index IX_Suppliers_SN_SC_Clustered
85 on suppliers (SupplierName, SupplierCity)
86;
87go
88
89-- 3.2 --
90-- Weil es nur einen gruppierten Index geben darf und das ist der Primary key
91
92-- 3.3 --
93create nonclustered index IX_Suppliers_SN_SC_NonClustered
94 on suppliers (SupplierName, SupplierCity)
95;
96go
97
98-- 3.4 --
99-- Man erstellt den primary key in einer extra zeile als non clustered
100
101-- 3.5 --
102select *
103 from sys.key_constraints
104;
105go
106
107select *
108 from sys.foreign_keys
109;
110go
111
112alter table supplierparts
113 drop constraint supplierparts_suppliers_fk
114;
115go
116
117alter table suppliers
118 drop constraint suppliers_pk
119;
120go
121
122alter table suppliers
123 add constraint suppliers_pk
124primary key nonclustered(supplierID)
125;
126go
127
128alter table supplierparts
129 add constraint supplierparts_suppliers_fk
130foreign key (suppliers_supplierid) references suppliers(supplierid)
131 on delete cascade
132 on update cascade
133;
134go
135
136-- 3.6 --
137
138select name, type_desc
139 from sys.indexes
140where object_id = (select object_id
141 from sys.tables
142 where name = 'suppliers'
143 )
144;