SQLServer创建索引的5种方法
前期准备: create table Employee ( ID int not null primary key,Name nvarchar(4),Credit_Card_ID varbinary(max)); --- 小心这种数据类型。
go
说明:本表上的索引,都会在创建下一个索引前删除。 创建聚集索引方法 1、ALTER TABLE table_name ADD CONSTRAINT cons_name priamry KEY(columnname ASC|DESC,[.....]) WITH (drop_existing = ON);
ALTER TABLE employee ADD CONSTRAINT pk_for_employee PRIMARY KEY CLUSTERED (id);
go
这个是一种特别的方法,因为在定义主键的时候,会自动添加索引,好在加的是聚集索引还是非聚集索引是我们人为可以控制的。 通过sp_helpindex 可以查看表中的索引 execute sp_helpindex @objname = 'Employee'; go 注意:这个索引是无法删除的,不信! 你去删一下 drop index Employee.PK__Employee__3214EC277D95E615;
go
方法 2、create clustered index ix_name on table_name(columnName ASC|DESC[,......]) with (drop_existing = on);
create clustered index ix_clu_for_employee_ID on Employee(ID);
go
查看创建的索引 创建复合索引create index ix_com_Employee_IDName on Employee (ID,Name)with (drop_existing = on);
这样就算是创建一个复合索引了,不过脚下的路很长,我们看下一个复合索引的例句: create index ix_com_Employee_IDCreditCardID on Employee(ID,Credit_Card_ID);
看到这句话,你先问一下自己它有没有错! 可以发现它错了,varbinary是不可以建索引的。 创建覆盖索引create index index_name on table_Name (columnName ASC|DESC[,......]) include(column_Name_List)with (drop_existing = on);
create index ix_cov_Employee_ID_Name on Employee (ID) include(Name);
go
首先,覆盖索引它只是非聚集索引的一种特别形式,下文说的非聚集索引不包涵覆盖索引,当然这个约定只适用于这一段话,这样做的目的是为了说明各中的区别。 首先:
创建唯一索引create unique index index_name on table_name (column ASC|DESC[,.....])with (drop_existing = on);
正如我前面所说,在创建表上的索引前,我会删除表上的所有索引,这里为什么我要再说一下呢!因为我怕你忘了。二来这个例子用的到它。 insert into Employee(ID,Name) values(1,'AAA'),(1,'BBB');
这下我们为表加唯一索引,它定义在ID这个列上 create unique index ix_uni_Employee_ID on Employee(ID);
go -- 可以想到因为ID有重复,所以它创建不了。
结论 1、 如果在列上有重复值,就不可以在这个列上定义,唯一索引。 下面我们把表清空: truncate table Employee; 接下来要做的就是先,创建唯一索引,再插入重复值。 create unique index ix_uni_Employee_ID on Employee(ID);
go
insert into Employee(ID,'BBB');
go
结论 2、 定义唯一索引后相应的列上不可以插入重复值。 筛选索引create index index_name on table_name(columName) where boolExpression;
create index ix_Employee_ID on Employee(ID) where ID>100 and ID< 200;
go
只对热点数据加索引,如果大量的查询只对ID 由 100 ~ 200 的数据感兴趣,就可以这样做。
总结:BTree 索引有聚集与非聚集之分。 非聚集索引分 最后说一下这个with (drop_existing = on|off),加上这个的意思是如果这个索引还在表上就drop 掉然后在create 一个新的。特别是在聚集索引上使用这个就可以不会引起非聚集索引的重建。 with (online = on|off) 创建索引时用户也可以访问表中的数据, with(pad_index = on|off fillfactor = 80); fillfactor 用来设置填充百分比,pad_index 只是用来连接fillfactor 但是它又不能少,这点无语了。 with(allow_row_locks = on|off | allow_page_locks = on |off); 是否允许页锁 or 行锁 with (data_compression = row | page ); 这样可以压缩索引大小 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |