4

我有一个索引视图,但是当我在该视图上运行查询时,未应用基于视图构建的索引,并且查询在没有索引的情况下运行。下面是我的虚拟脚本:Tables + View+ Index on 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

你能帮我解决这个问题吗?

4

1 回答 1

4

您需要使用NOEXPAND提示。除非您在 Enterprise Edition 引擎上,否则 SQL Server 不会考虑匹配没有此索引的视图(即使在查询中引用了视图名称)。

SELECT COUNT(PStatusID) 
FROM [TestView] 
     WITH (NOEXPAND) -- this line
WHERE [PStatusID]=1

这应该会给你第一个便宜得多的计划

计划

于 2012-01-02T11:16:08.633 回答