SQLSERVER 创建索引视图注意事项

一、注意点

1、索引视图所引用的基表必须在同一个数据库中,不是用union all引用多个数据库的表;

2、创建索引视图时要加上with schemabinding;

3、创建索引视图时要指定表所属的架构;

4、在创建索引视图的select语句时,不能使用*,必须指定具体的列名;

5、只能为索引视图创建唯一聚集索引;

6、索引视图中的select包含一个或多个 UNION、INTERSECT 或 EXCEPT 运算符时,不能创建索引(创建视图时不报错,创建索引的时候会报错);

 二、操作步骤

--1.创建索引视图
create view v_customer_sch_index with schemabinding
as
select Col1,Col2 from dbo.customer
go

--2.创建普通视图
create view v_customer
as
select Col1,Col2 from dbo.customer
union all
select Col1,Col2 from dbo.customer2007
union all
select Col1,Col2 from dbo.customer2008
go

--3.为索引视图创建唯一聚集索引
create unique clustered index cust_uniquetb on v_customer_sch_index(Col1)
go

--4.查看聚集索引有多少行以及视图占用多少空间
EXECUTE sp_spaceused 'v_customer_sch_index'

 --5.查询索引视图强制走索引(with (NOEXPAND) )

select * from run.dbo.v_customer_sch_index with (NOEXPAND) where Col1='998628'

 --6.再次插入数据的执行计划

INSERT INTO run.dbo.customer SELECT * FROM run.dbo.customer2008

猜你喜欢

转载自www.cnblogs.com/mengcheng9300/p/12915823.html