文章目录
1.索引介绍
索引是一种重要的数据库对象,它可以和基本表或者视图建立关联。当表的数据量比较大时,查询操作会比较耗时。建立索引是加快查询速度的有效手段。数据库索引类似于图书后面的索引,能快速定位到需要查询的内容。用户可以根据应用环境的需要,在基本表上建立一个或多个索引,以提供多种存取路径,加快查找速度。
在SQL Server 2012中,索引主要有聚集索引和非聚集索引两种。
1. 聚集索引
聚集索引定义中包含聚集索引列。聚集索引根据数据行的键值在表或视图中排序来存储这些数据行。因此数据表的物理存储顺序和索引是一致的。每个表有且只能有一个聚集索引,因为数据行本身只能按一个顺序进行排序。
2. 非聚集索引
非聚集索引具有独立于数据行的结构。非聚集索引包含非聚集索引键值,并且每个键值项都有指向包含该键值的数据行指针。从非聚集索引中的索引行指向数据行的指针称为行定位器,行定位器的结构取决于数据页是存储在堆中还是聚集表中,对于堆,行定位器是指向行的指针,对于聚集表,行定位器是聚集索引键。
2.创建索引
①创建非聚集索引
使用SSMS工具
- 在数据库中,打开需要创建索引的数据表,右击“索引”,选择新建索引。
- 选择“非聚集索引”,进入“新建索引”对话框
- 在“索引名称”中输入需要新建的索引名
- 在“索引键列”中单击“添加”按钮,弹出选择列窗口,选择需要设为索引的属性列,点击确定返回
- 点击确定,在“索引”中可以看到索引创建成功。
使用SQL方式
语法格式:
CREATE [NONCLUSTERED] INDEX <索引名>
ON <视图或数据表>(属性列)
使用示例:为student表中的StuName属性建立非聚集索引
create nonclustered index IX_student_StuName
on student(StuName)
②创建聚集索引
使用SSMS工具
- 在数据库中,打开需要创建索引的数据表,右击“索引”,选择新建索引。
- 选择“聚集索引”,进入“新建索引”对话框
- 在“索引名称”中输入需要新建的索引名
- 在“索引键列”中单击“添加”按钮,弹出选择列窗口,选择需要设为索引的属性列,点击确定返回
- 点击确定,在“索引”中可以看到索引创建成功。
使用SQL方式
语法格式:
CREATE CLUSTERED INDEX <索引名>
ON <视图或数据表>(属性列)
使用示例:为student表中的StuID属性建立聚集索引
create clustered index IX_student_StuID
on student(StuID)
3.索引启用与禁用
禁用索引可以防止用户访问索引,对于非聚集索引,则可以防止用户访问基本表数据。索引被禁用后会一直保持禁用状态,直到它被重新生成或被删除。
禁用索引
使用SSMS工具
- 右击需要禁用的索引名,选择禁用
- 弹出“禁用索引”对话框,点击确定,即可禁用索引。右击索引,选择属性,可以看到索引已被禁用
使用SQL方式
语法格式:
ALTER INDEX <索引名>
ON <数据表或视图> DISABLE
使用示例:禁用IX_student_StuName索引
alter index IX_student_StuName
on student disable
启用索引
使用SSMS工具
- 右击需要启用的索引名,选择“重新生成”
- 弹出“重新生成索引”对话框,点击确定
- 右击索引,选择“属性”,可以看到索引处于就绪状态。
使用SQL方式
语法格式:
ALTER INDEX <索引名>
ON <数据表或视图> REBUILD
使用示例:禁用IX_student_StuName索引
alter index IX_student_StuName
on student rebuild
4.查看索引
语法格式:
--查看数据表或视图中的索引
SP_HELPINDEX <数据表或视图>
使用示例:查看student表中的索引
use schoolDB
go
sp_helpindex student
5.删除索引
使用SSMS工具
- 选择需要删除的索引,右击,选择删除
- 弹出删除对象对话框,点击确定,即可完成索引删除
使用SQL方式
语法格式:
DROP INDEX <索引名> ON <数据表或视图>
使用示例:删除student表中的IX_student_StuName索引
drop index IX_student_StuName
on student