SQL Server 拒绝的筛选索引提示

Tia*_*ago 3 sql-server-2008 sql-server filtered-index

我有一个 SQL Server 没有使用的筛选的非聚集索引。我很确定优化器正在做正确的选择,但我想强制它使用该索引运行,以便我可以比较计划并了解为什么它更昂贵。

我已经从查询中删除了所有内容,我只是选择了正在过滤的列。

索引定义:

CREATE INDEX idx_all
    ON tbl_test (CommentDateTime, name)
    INCLUDE (comment, CommentByType)
    WHERE CommentByType='INT';
Run Code Online (Sandbox Code Playgroud)

我试图运行的查询是:

SELECT CommentByType
FROM tbl_test WITH (INDEX (idx_all))
WHERE CommentByType='INT';
Run Code Online (Sandbox Code Playgroud)

并且 SQL Server 返回以下错误:

Query processor could not produce a query plan because of the hints defined in this query.
Resubmit the query without specifying any hints and without using SET FORCEPLAN.
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多关于被过滤的列被包含在键中或作为包含列的信息,但没有任何帮助。

在此处输入图片说明

Mar*_*ith 10

我可以在带有PARAMETERIZATION FORCED.

CREATE DATABASE D1

ALTER DATABASE D1 SET PARAMETERIZATION FORCED

GO

USE D1

CREATE TABLE tbl_test
(
CommentDateTime DATETIME,
name VARCHAR(50),
comment VARCHAR(50),
CommentByType VARCHAR(10)
);

CREATE INDEX idx_all
    ON tbl_test (CommentDateTime, name)
    INCLUDE (comment, CommentByType)
    WHERE CommentByType='INT';

SELECT CommentByType
FROM tbl_test WITH (INDEX (idx_all))
WHERE CommentByType='INT'
--OPTION (RECOMPILE)
;
Run Code Online (Sandbox Code Playgroud)

然后文字被参数化,不再保证过滤后的索引会匹配

where CommentByType = @0
Run Code Online (Sandbox Code Playgroud)

在这种情况下OPTION (RECOMPILE)允许提示成功。

  • @MrKudz - 因为带有 `where CommentByType = @0` 的参数化计划需要适用于 `@0` 的任何可能值 - 不仅仅是 `'INT'`,所以不能保证过滤的索引是合适的。即`SELECT CommentByType FROM tbl_test WITH (INDEX (idx_all)) WHERE CommentByType='SOMEOTHERVALUE'` 不起作用。 (2认同)