给定以下架构:
create table dbo.SomeTable
(
ID int primary key identity(1, 1),
SomeColumn varchar(50)
);
create index IX_SomeColumn on dbo.SomeTable (SomeColumn);
并用一些数据填充它:
declare @i int = 1000;
while @i > 0 begin
set @i = @i - 1;
insert dbo.SomeTable (SomeColumn)
values (convert(varchar, @i))
end
此查询执行索引查找:
select ID
from dbo.SomeTable
where SomeColumn = '431'
当此查询执行索引扫描时:
select ID
from dbo.SomeTable
where case when SomeColumn = '431' then 1 else 0 end = 1
有没有办法让后者(或类似的东西)改为执行索引查找?
我问是因为我希望能够将 case when
放入 View 的选择列表中并在 where
子句中使用它,但它会如果我无法让 SQL Server 执行索引查找,则永远不会像原始表单那样执行。
最佳答案
您可以在那里进行查找的唯一方法是使 case when SomeColumn = '431' then 1 else 0 end
表达式成为计算列并索引计算列。
然后您应该会发现该表达式与允许查找的计算列匹配(以维护额外索引为代价)。
(如果您遇到自动参数化阻止匹配的问题,添加冗余 1=1
将阻止这种情况。SQL Fiddle with plan showing a seek)
关于sql-server - CASE WHEN 在 SQL Server : seek vs scan 中使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245628/