40人参与 • 2026-07-24 • MsSqlserver
本文对sqlserver中的索引进行一个知识总结。
未创建聚集索引的表称为堆表,数据无序追加,无统一排序。
-- 创建堆表(无聚集索引)
create table testdata (
testid integer, testname varchar(255), testdate date,
testtype integer, testdata1 integer, testdata2 varchar(100),
testdata3 xml, testdata4 varbinary(max), testdata4_filetype varchar(3)
);
alter table testdata rebuild; -- 重建堆表
drop table testdata; -- 删除表b+树结构,索引键与完整行数据存储在叶子节点。一张表最多1个聚集索引,创建后不再为堆表。
create clustered index ix_testdata_testid on dbo.testdata (testid); alter index ix_testdata_testid on testdata rebuild with (online = on); -- 在线重建 drop index ix_testdata_testid on testdata with (online = on); -- 在线删除
b+树结构,叶子节点不存完整行,仅存行定位指针(指向聚集索引键或堆表的rid)。
create index ix_testdata_testdate on dbo.testdata (testdate); alter index ix_testdata_testdate on testdata rebuild with (online = on); drop index ix_testdata_testdate on testdata;
按列存储的特殊索引,分为聚集列存储与非聚集列存储两种。
-- 创建聚集列存储索引
create clustered columnstore index cix_testdata_testtype on dbo.testdata (testtype)
with (data_compression = columnstore);
drop index cix_testdata_testtype;专用于 xml 类型字段,分为主xml索引和二级xml索引(path/value/property),前置要求:表必须有主键聚集索引。
create primary xml index pxml_testdata_testdata3 on testdata (testdata3);
create xml index xmlpath_testdata_testdata3 on testdata (testdata3)
using xml index pxml_testdata_testdata3 for path;
create xml index xmlproperty_testdata_testdata3 on testdata (testdata3)
using xml index pxml_testdata_testdata3 for property;
create xml index xmlvalue_testdata_testdata3 on testdata (testdata3)
using xml index pxml_testdata_testdata3 for value;将文本拆分为分词(token)构建索引,索引文件独立存放于全文目录,不混存于数据文件。
create fulltext catalog fulltextcatalog as default;
create fulltext index on dbo.testdata (testdata4 type column testdata4_filetype)
key index pk_testdata with stoplist = system;
alter fulltext catalog fulltextcatalog rebuild;
drop fulltext index on dbo.testdata;非聚集索引扩展:将指定字段存入叶子节点,实现"类聚集索引"效果,免去回表。支持 text/ntext/image 外的绝大多数类型。
create nonclustered index ix_testdata_testdate_inctestdata3 on testdata (testdate)
include (testdata3);
sql server 不直接支持函数索引,通过持久化计算列模拟实现。
alter table testdata add testdateplus7days as dateadd(day, 7, testdate) persisted; create nonclustered index ix_testdata_testdate_plus7days on testdata (testdateplus7days);
带 where 条件的非聚集索引,缩小索引体积、降低维护成本。仅当查询条件与索引 where 完全匹配时优化器才会选用。
create index ix_testdata_testdate_testtypeeq1 on testdata (testdate) where testtype = 1;
设计思路:查询所有字段要么是索引键,要么在 include 中,完全消除回表,性能最优。
create index ix_testdata_testdate_testtype_alldata on testdata (testdate, testtype)
include (testdata1, testdata2, testdata3, testdata4);
-- 该查询完全走索引,无需访问原表
select testdata1, testdata2, testdata3, testdata4
from testdata
where testdate > current_timestamp - 1 and testtype = 1;到此这篇关于sql server 索引知识汇总的文章就介绍到这了,更多相关sql server 索引内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论