I have a stored procedure in SQL Server 2000 that performs a search based on parameter values. For one of the parameters passed in, I need a different WHERE
clause depending on its value - the problem is that the 3 values would be where MyColumn
IS NULL
IS NOT NULL
ANY VALUE (NULL AND NOT NULL)
(essentially noWHERE
clause)
I'm having some mental block in coming up with the correct syntax. Is this possible to do in one select statement without performing some IF @parameter BEGIN ... END
branching?
Here is how you can solve this using a single
WHERE
clause:A naïve usage of the CASE statement does not work, by this I mean the following:
It is possible to solve this using a case statement, see onedaywhen's answer
I've had success with this solution. It's almost like Patrick's, with a little twist. You can use these expressions separately or in sequence. If the parameter is blank, it will be ignored and all values for the column that your searching will be displayed, including NULLS.
An other way of CASE:
If
@value
isNULL
, it will compareMyColumn
to itself, ignoring@value = no where
clause.IF
@value
has a value (NOT NULL
) it will compareMyColumn
to@value
.Reference: COALESCE (Transact-SQL).
This is how it can be done using
CASE
:You could just do something like this:
Something like that.