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 no WHERE
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?
The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Note: IS NULL and IS NOT NULL can be used in the same SQL query in WHERE clause in any order and in any combination as per the requirement.
<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.
Here is how you can solve this using a single WHERE
clause:
WHERE (@myParm = value1 AND MyColumn IS NULL) OR (@myParm = value2 AND MyColumn IS NOT NULL) OR (@myParm = value3)
A naïve usage of the CASE statement does not work, by this I mean the following:
SELECT Field1, Field2 FROM MyTable WHERE CASE @myParam WHEN value1 THEN MyColumn IS NULL WHEN value2 THEN MyColumn IS NOT NULL WHEN value3 THEN TRUE END
It is possible to solve this using a case statement, see onedaywhen's answer
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