I wonder if there is any wise way to rewrite the following query so that the indexes on columns get used by optimizer?
SQL Server is not very good in optimizing the OR predicates.
Use this:
SELECT key3
FROM or_table
WHERE @key1 = 0
AND @key2 = 0
UNION ALL
SELECT key3
FROM or_table
WHERE @key1 = 0
AND @key2 <> 0
AND key2 = @key2
UNION ALL
SELECT key3
FROM or_table
WHERE @key2 = 0
AND @key1 <> 0
AND key1 = @key1
UNION ALL
SELECT key3
FROM or_table
WHERE @key1 <> 0
AND @key2 <> 0
AND key1 = @key1
AND key2 = @key2
SQL Server will look to the values of the variables prior to executing the queries and will optimize the redundant queries out.
This means that only one query of four will be actually executed.