我想根据两列是否相等来进行快速查找。我试图使用带有索引的计算列,但是SQL Server似乎没有使用它。如果仅使用带有索引的静态填充的位列,则会得到预期的索引查找。
似乎还有其他类似的问题,但是没有一个问题集中在为什么不使用索引上。
测试表:
CREATE TABLE dbo.Diffs
(
Id int NOT NULL IDENTITY (1, 1),
DataA int NULL,
DataB int NULL,
DiffPersisted AS isnull(convert(bit, case when [DataA] is null and [DataB] is not null then 1 when [DataA] <> [DataB] then 1 else 0 end), 0) PERSISTED ,
DiffComp AS isnull(convert(bit, case when [DataA] is null and [DataB] is not null then 1 when [DataA] <> [DataB] then 1 else 0 end), 0),
DiffStatic bit not null,
Primary Key (Id)
)
create index ix_DiffPersisted on Diffs (DiffPersisted)
create index ix_DiffComp on Diffs (DiffComp)
create index ix_DiffStatic on Diffs (DiffStatic)
和查询:
select Id from Diffs where DiffPersisted = 1
select Id from Diffs where DiffComp = 1
select Id from Diffs where DiffStatic = 1
COALESCE
;我相信该CASE
语句已经保证可以返回0
或1
,但是ISNULL
它只存在,因此SQL Server将为BIT
计算列生成非空值。但是,COALESCE
仍将产生可为空的列。因此,无论是否带有,此更改的影响之一COALESCE
是计算列现在可以为空,但可以使用索引查找。