Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

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

  1. IS NULL
  2. IS NOT NULL
  3. 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?

like image 686
Russ Cam Avatar asked May 01 '09 09:05

Russ Cam


People also ask

IS NOT NULL in WHERE clause SQL Server?

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.

Can we use NULL in WHERE clause?

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 is not NULL and != The same in SQL?

<> 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.


1 Answers

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

like image 182
Patrick McDonald Avatar answered Oct 13 '22 07:10

Patrick McDonald