我有一个索引视图,但是当我在该视图上运行查询时,未应用基于View构建的索引,并且查询在没有索引的情况下运行。下面是我的虚拟脚本: 表+视图+视图索引
CREATE TABLE P_Test
(
[PID] INT IDENTITY,
[TID] INT,
[StatusID] INT
)
CREATE TABLE T_Test
(
[TID] INT IDENTITY,
[FID] INT,
)
CREATE TABLE F_Test
(
[FID] INT IDENTITY,
[StatusID] INT
)
GO
INSERT INTO F_Test
SELECT TOP 1000 ABS(CAST(NEWID() AS BINARY(6)) %10) --below 100
FROM master..spt_values
INSERT INTO T_Test
SELECT TOP 10000 ABS(CAST(NEWID() AS BINARY(6)) %1000) --below 1000
FROM master..spt_values,
master..spt_values v2
INSERT INTO P_Test
SELECT TOP 100000 ABS(CAST(NEWID() AS BINARY(6)) %10000) --below 10000
,
ABS(CAST(NEWID() AS BINARY(6)) %10)--below 10
FROM master..spt_values,
master..spt_values v2
GO
CREATE VIEW [TestView]
WITH SCHEMABINDING
AS
SELECT P.StatusID AS PStatusID,
F.StatusID AS FStatusID,
P.PID
FROM dbo.P_Test P
INNER JOIN dbo.T_Test T
ON T.TID = P.TID
INNER JOIN dbo.F_Test F
ON T.FID = F.FID
GO
CREATE UNIQUE CLUSTERED INDEX [PK_TestView]
ON [dbo].[TestView] ( [PStatusID] ASC, [FStatusID] ASC, [PID] ASC )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
现在,当我运行以下查询时,未应用[PK_TestView]索引:
SELECT PStatusID ,
FStatusID ,
PID FROM [TestView]
SELECT PStatusID ,
FStatusID ,
PID FROM [TestView]
WHERE [PStatusID]=1
SELECT COUNT(PStatusID) FROM [TestView]
WHERE [PStatusID]=1
你可以帮我解决这个问题吗?
答案 0 :(得分:4)
您需要使用NOEXPAND
提示。除非您使用Enterprise Edition引擎,否则SQL Server将不考虑在没有此情况下匹配索引视图(即使查询中引用了视图名称)。
SELECT COUNT(PStatusID)
FROM [TestView]
WITH (NOEXPAND) -- this line
WHERE [PStatusID]=1
这应该会给你第一个,便宜得多的计划