一、 主建的創建與刪除
1. 創建表時同時創建主鍵(加primary key)
Create Table Book
(
ID int identity(1,1) primary key,
Name nvarchar(50) not null,
StudentID int not null
)
2. 用SQL語句單獨創建主鍵
1)創建主鍵同時會自動在該主鍵上創建聚集索引
語句:alter table [表名] add constraint PK_Book_ID primary key (主鍵列名)
例如:alter table Book add constraint PK_Book_ID primary key (ID)
2)創建主鍵但不在該主鍵上創建聚集索引(但會自動創建非聚集索引)
語句:alter table [表名] add constraint PK_Book_ID primary key (主鍵列名)
例如:alter table Book add constraint PK_Book_ID primary key (ID)
3. 用SQL語句刪除主鍵
語句:alter table [表名] drop constraint [主鍵名]
例如:alter table Book drop constraint [PK_Book_ID]
二、 索引的創建與刪除
1. 創聚集索引
語句:create clustered index [聚集索引名] on [表名](要創建聚集索引的列名asc|desc) with(drop_existing = on)
例如:create clustered index IX_CLU_Book_ID on Book(ID)
2. 創非集索引
語句:create index [非聚集索引名] on [表名](要創建非聚集索引的列名 asc|desc) with(drop_existing = on)
例如:create index IX_ Book_Name on Book(Name)
3. 創復合索引
語句:create index [復合索引名] on [表名](列名1 asc|desc, 列名2 asc|desc) with(drop_existing = on)
例如:create index IX_com_Book_IDName on Book (ID,Name)
4. 創建唯一索引
語句:create unique index index_name on table_name (column ASC|DESC[,.....])with (drop_existing = on)
例如:create unique index IX_Book_ID on Book (ID)
5. 創建覆蓋索引
語句:create index index_name on table_Name (columnName ASC|DESC[,......]) include(column_Name_List)with (drop_existing = on)
例如:create index ix_cov_Book_ID_Name on Book (ID) include(Name)
說明:覆蓋索引它只是非聚集索引的一種特別形式,是把數據加到非聚集索引上。
覆蓋索引和普通非聚集索引的區別:
1)非聚集索引不包涵數據,通過它找到的只是文件中數據行的引用(表是堆的情況下)或是聚集索引的引用,SQL Server要通這個引用去找到相應的數據行。
2)正因為非聚集索引它沒有數據,才引發第二次查找。
3)覆蓋索引就是把數據加到非聚集索引上,這樣就不需要第二次查找了。這是一種以空間換性能的方法。
6. 篩選索引
語句:create index index_name on table_name(columName) where boolExpression
例如:create index IX_Book_ID on Book(ID) where ID>100 and ID< 200
說明:只對熱點數據加索引,如果大量的查詢只對ID 由 100 ~ 200 的數據感興趣,就可以這樣做。
1)可以減小索引的大小
2)為據點數據提高查詢的性能
7. 刪除索引
語句:drop index table_Name.Index_Name
例如:drop index Book. IX_ Book_Name
8. 查看表中索引存儲過程
execute sp_helpindex @objname = '表名'
總結:
BTree 索引有聚集與非聚集之分。
就查看上到聚集索引性能比非聚集索引性能要好。
非聚集索引分,覆蓋索引,唯一索引,復合索引(當然聚集索引也有復合的,復合二字,只是說明索引,引用了多列),一般非聚集索引就查看上,非聚集索引中覆蓋索引的性能比別的非聚集索引性能要好,它的性能和聚集索引差不多,可是它會用更多的磁盤空間。
最后說一下這個
1)with (drop_existing = on|off),加上這個的意思是如果這個索引還在表上就drop 掉然后在create 一個新的。特別是在聚集索引上用使用這個就可以不會引起非聚集索引的重建。
2)with (online = on|off) 創建索引時用戶也可以訪問表中的數據,
3)with(pad_index = on|off fillfactor = 80); fillfactor 用來設置填充百分比,pad_index 只是用來連接fillfactor 但是它又不能少。
4)with(allow_row_locks = on|off | allow_page_locks = on |off); 是否允許頁鎖 or 行鎖
5)with (data_compression = row | page ); 這樣可以壓縮索引大小
