我有以下 SQL:
CREATE TABLE tbFoo(
a varchar(50) NULL,
)
CREATE NONCLUSTERED INDEX IX_tbFoo_a ON tbFoo
(
a 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)
insert into tbFoo select null
insert into tbFoo select 'test'
以下两个查询工作正常并按预期使用我的索引:
select * from tbFoo where a='test'
select * from tbFoo where a is null
现在,假设我想将比较值存储在一个变量中,如下所示:
declare @a varchar(50)
select @a = NULL
如果@a 为空,则以下查询将不会返回预期结果,因为我应该使用“is”运算符而不是“=”
select * from tbFoo where a=@a
以下将起作用,但如果@a 为空,则会进行表扫描(因为“测试”行会强制评估第二个括号)
select * from tbFoo where (a is null and @a is null) or (a=@a)
最终,我想出了这个解决方案,它工作正常并使用我的索引:
select * from tbFoo where (a is null and @a is null) or (@a is not null and a=@a)
我对情况的分析正确吗?
有没有更好的方法来处理这种情况?