考虑以下模式:CASE WHEN在SQL Server索引的使用:寻求VS扫描
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
放入视图的选择列表中,并在where
子句中使用它,但如果我无法获得,它将永远不会与原始形式一样好SQL Server进行索引查找。
你的第二个查询不SARGEBLE。除非将其应用于表中的每一行,否则无法知道“CASE”语句的值。这就是为什么你要扫描。当然,很显然,如果'SomeColumn ='431'''CASE'语句只会返回1,但是SQL Server看起来不够深入。 –