views:

114

answers:

2

I have a Select like the one below in a stored procedure (shortened for brevity). @param is a parameter to the stored procedure which can be NULL.

SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ...

I would like the EXISTS statement (the part in bold) to be used only when @param has a value otherwise ignore it.

I don't want to use dynamic SQL or temporary tables if possible. I am trying to use a CASE statement to work with the EXISTS statement but with not much luck.

+2  A: 
WHERE (@Param IS NULL OR EXISTS (SELECT .... ))

Note that this isn't a guarantee - the query optimizer will do what it wants. But is should be smart enough to optimize the exists clause away.

Joel Coehoorn
The only thing you'd want to watch for then is that the stored procedure will cache the execution plan for the first case that is run; Probably want to mark the sproc as "WITH RECOMPILE" - lose the benefit of cached execution plan but gain an optimal plan for each call.
Chris Shaffer
What am I missing here? How will the EXISTS statement only be used when @Param has a value, in this example?
John Sansom
When param has a value, the first part of that expression is false and so the exists clause _will_ run. When param does not have a value, that where expression will always return true, so there's no need to call EXISTS. The only question is whether the query optimizer is smart enough to realize this.
Joel Coehoorn
+6  A: 

Using the OR in the WHERE clause will most likely by horrendously slow, especially if EXISTS.

Other options...

Union: only one will return rows

SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ...
UNION ALL
SELECT name FROM Table1 WHERE @param IS NULL AND ... AND ...

Conditional branch:

IF @param2 IS NULL
    SELECT name FROM Table1 WHERE ... AND ...
ELSE
    SELECT name FROM Table1 WHERE EXISTS (select .... from table2 Where param = @param AND ... AND ...) AND ... AND ...
gbn