I've got the following 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'
The two following queries work fine and use my index as expected :
select * from tbFoo where a='test'
select * from tbFoo where a is null
Now, let's pretend I want to store my comparison value in a variable, like this :
declare @a varchar(50)
select @a = NULL
The following query won't return the expected results if @a is null because I should use the "is" operator rather than "="
select * from tbFoo where a=@a
The following will work but will do a table scan if @a is null (because of the 'test' row which forces the evaluation of the second parenthesis)
select * from tbFoo where (a is null and @a is null) or (a=@a)
Eventually, I've came up with this solution, which works fine and uses my index :
select * from tbFoo where (a is null and @a is null) or (@a is not null and a=@a)
Is my analysis of the situation correct?
Is there a better way to handle this situation ?