I have 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 following two 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 say I want to store my comparison value in a variable, for example:
declare @a varchar(50)
select @a = NULL
The following query will not return the expected results if @a is null, because I have to use the "is" operator, not the "="
select * from tbFoo where a=@a
The following will work, but will scan the table if @a is null (because of the string "test", which forces the second bracket to be evaluated)
select * from tbFoo where (a is null and @a is null) or (a=@a)
In the end, I came up with this solution that 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)
Am I analyzing the situation correctly?
Is there a better way to handle this situation?