I am looking for opinions and possibly a concrete answer to the following.
This question applies for SQL Server version 2008 R2+
In a stored procedure, I have an optional query parameter of type DATE, lets call it @MyVar.
The stored procedure executes the following query:
SELECT A, B, C
FROM MyTable
WHERE MyTable.Field1 = ISNULL(@MyVar,MyTable.Field1)
What is the cost of doing the ISNULL(@MyVar,MyTable.Field1) if @MyVar is NULL? I am wondering if it's better to split the cases such as:
IF (@MyVar IS NULL)
SELECT A, B, C
FROM MyTable
ELSE
SELECT A, B, C
FROM MyTable
WHERE MyTable.Field1 = @MyVar
Thanks!
A more elegant approach would be:
SELECT A, B, C
FROM MyTable
WHERE MyTable.Field1 = @MyVar
OR @MyVar IS NULL
OPTION(RECOMPILE)
edit
Based on suggestion by @JamesZ, added option(recompile)
so that an index on field1
will be used (if it exists).
edit2 (Thanks @Y.B. for pointing it out.)
If field1
can be null
as well use something like:
SELECT A, B, C
FROM MyTable
WHERE MyTable.Field1 = @MyVar
OR (@MyVar IS NULL AND MyTable.Field1 IS NULL)
OPTION(RECOMPILE)
This already shows the problems with 'catch all' queries. You could also, for example, replace the AND
in the last query with OR
, which would give yet another (theoretical) result set, but could potentially be correct as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With