在sql中,建立视图索引
create unique clustered index clu_name on View_1(a)
无法在该视图上建立索引,因为该视图未绑定到框架
是不是视图不可以建立索引?
[解决办法]
格式:
CREATE VIEW Sales.vOrders
WITH SCHEMABINDING
AS
SELECT SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Revenue,
OrderDate, ProductID, COUNT_BIG(*) AS COUNT
FROM Sales.SalesOrderDetail AS od, Sales.SalesOrderHeader AS o
WHERE od.SalesOrderID = o.SalesOrderID
GROUP BY OrderDate, ProductID;
GO
--Create an index on the view.
CREATE UNIQUE CLUSTERED INDEX IDX_V1
ON Sales.vOrders (OrderDate, ProductID);
GO
--1.1创建索引视图
create view dbo.v_index_wcT
with schemabinding --必须要写
as
select wcid,
wcV,
wcDate
from dbo.wcT --必须要有架构,也就是:dbo.对象
go
--2.1在索引视图上创建唯一聚集索引
create unique clustered index idx_v_index_wcT
on dbo.v_index_wcT(wcid)
--2.2创建非聚集索引
create nonclustered index idx_v_index_wcT_wcV
on dbo.v_index_wcT(wcV)
IF OBJECT_ID('test1','u') IS NOT NULL
DROP TABLE test1
CREATE TABLE test1(id int)
IF OBJECT_ID('test2','u') IS NOT NULL
DROP TABLE test2
CREATE TABLE test2(id int)
go
IF OBJECT_ID('t1','v') IS NOT NULL
DROP VIEW t1
go
CREATE VIEW t1
WITH SCHEMABINDING
AS
SELECT a.id
FROM dbo.test1 a INNER JOIN dbo.test2 b ON a.id=b.id
GO
IF OBJECT_ID('t2','V') IS NOT NULL
DROP VIEW t2
go
CREATE VIEW t2
WITH SCHEMABINDING
AS
SELECT test1.id
FROM dbo.test1 INNER JOIN dbo.t1 ON test1.id=t1.id
GO
create unique clustered index clu_name on t1(id)
create unique clustered index clu_name on t2(id)
/*
Msg 1937, Level 16, State 1, Line 1
Cannot create index on view 'tempdb.dbo.t2' because it references another view 'dbo.t1'. Consider expanding referenced view's definition by hand in indexed view definition.
*/