索引基礎

-- =============================================               
-- Author:      餘波(杭州)               
-- Create date: 2011/09/29               
-- Description: 索引基礎              
-- ============================================= 
------測試表結構
create table test
(
	id int,
	name int
)
------插入測試數據
insert into test
select 1,1
union
select 2,2
union
select 3,3
union
select 4,4
------在表上創建索引
------語法
--create [unique][nonclustered|clustered] index index_name on tablename(column_name)
--1、創建唯一/非唯一 聚集索引
create unique clustered index u_clu_index on test(a)
create clustered index u_clu_index on test(a)
--2、創建唯一/非唯一 非聚集索引
create unique nonclustered index u_nclu_index on test(a)
create nonclustered index u_nclu_index on test(a)
------在試圖上創建索引
create view v_test
with schemabinding
as
select id from dbo.test
--建立視圖索引的前提有四個,都要在創建視圖時滿足
--1、要用with schemabinding綁定schema
--2、視圖中用到的表格式要滿足schema.test,如dbo.test,如果寫成test,則報錯
--3、select中要指定列名,如id,不能使用* 
--4、視圖上要建立索引,先要建立唯一的聚集索引,只有建立了唯一的聚集索引才能建立非聚集索引

--在視圖上建立唯一聚集索引
create unique clustered index v_clu_index on v_test(id)
--在視圖上建立唯一聚集索引之後,可以建立非聚集索引
create nonclustered index v_nclu_index on v_test(name)

-------刪除索引
drop index test.u_clu_index --eg 
-------刪除由主鍵創建生成的聚集索引的話,需要刪除主鍵約束
alter table test
drop constraint pk_test

-------禁用表索引
alter index u_uclu_index on test disable
--禁用聚集索引和禁用非聚集索引的效果是不一樣的
--因爲聚集索引的葉級別存儲的是實際數據頁本身
--而非聚集索引的葉級別存儲的是指向實際數據頁的指針
--所以當禁用聚集索引時,就無法訪問到實際表數據
--而禁用非聚集索引,則只是指針,不會影響對實際表數據的訪問
--如下:
--禁用聚集索引
alter index u_clu_index on test disable
select * from test
--當執行select 時得到以下提示
/*
The query processor is unable to produce a plan because the index 'u_clu_index' on table or view 'test' is disabled.
*/

--禁用非聚集索引
alter index u_uclu_index on test disable
select * from test
---當執行select時,能得到表數據,結果如下
/*
id	name
1	1
2	2
3	3
4	4	
*/

--當表上的聚集索引爲disable時,則不能再表上創建非聚集索引
--例如
alter index u_clu_index on test disable
create index c_test on test(id)
--以上語句會得到下面的提示
/*
Cannot create nonclustered index 'c_test' on table 'test' because its clustered index is disabled.
*/

----以上禁用規則是針對表來說的,如果是視圖的話,不管是禁用聚集索引還是非聚集索引
--禁用後,都能通過視圖訪問表數據


--補充:
--1、聚集索引列選擇:經常出現在範圍查詢的關鍵字中(如between、大於和小於等關鍵字)
--2、經常更新或非唯一的列不適合建聚集索引
--3、非聚集索引選擇列:出現在關鍵字where、order by、join中的列;高選擇性且選擇返回值少的列
--4、索引鍵不支持大型數據類型如:varchar(max),nvarchar(max),text,ntext,image,varbinary(max),nvarbinary(max),xml
--5、如果表中已經存在非聚集索引,則新建聚集索引會重建非聚集索引
--6、NULL值在唯一索引中是允許的,但是隻能出現一次
--7、查看索引元數據 exec sp_helpindex 'tablename'

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章