SQL SERVER 2008 开发系列(一)B

Posted on 2008-09-15 22:46  狂笑人生  阅读(165)  评论(0)    收藏  举报

索引包含列应用 (补充说明)

您可以通过将非键列添加到非聚集索引的叶级,扩展非聚集索引的功能。通过包含非键列,可以创建覆盖更多查询的非聚集索引。这是因为非键列具有下列优点:

· 它们可以是不允许作为索引键列的数据类型。

· 在计算索引键列数或索引键大小时,数据库引擎不考虑它们。

当查询中的所有列都作为键列或非键列包含在索引中时,带有包含性非键列的索引可以显著提高查询性能。这样可以实现性能提升,因为查询优化器可以在索引中找到所有列值;不访问表或聚集索引数据,从而减少磁盘 I/O 操作。

当索引包含查询引用的所有列时,它通常称为“覆盖查询”。

use Blog
go

--创建索引包含列演示数据表
Create Table IndexInclude
(
EmployeeID int identity(1,1) primary key not null,
NationalIDNumber nvarchar(15) not null,
ContactID int not null,
LoginID nvarchar(256) not null,
ManagerID int null,
Title nvarchar(50) not null
)

go

select * from IndexInclude
go

--插入测试数据
insert into IndexInclude
select NationalIDNumber,ContactID,LoginID,ManagerID,Title from AdventureWorks.HumanResources.Employee

go

set statistics io on

--查询
select * from IndexInclude where NationalIDNumber='685233686'

--没有创建非聚集索引时,执行计划如下图所示:

clip_image002

逻辑读次数:8次;

--创建非聚集索引,并且包含列
CREATE INDEX IX_IndexInclude_NationalIDNumber      
ON IndexInclude (NationalIDNumber)      
INCLUDE (ContactID,LoginID,ManagerID,Title); 
go

--查询
select * from IndexInclude where NationalIDNumber='685233686'

创建非聚集索引,并且包括非键列时,执行计划如下图所示:

clip_image004

逻辑读次数:2次,性能明显提升了;

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3