Search code examples
sqlsql-servercomparisonansi-sql

Single SQL query to tackle NULL and non-NULL values


I have a stored procedure that has a parameter that can be either NULL or non-NULL value. I need to compare this parameter in the WHERE clause. If the parameter is non-NULL,

where ...
and parameter = non-NULL-value

will work.

But when the parameter will be null, it will not be ANSI-compliant:

where ...
and parameter = NULL

I don't want to write two separate queries. How do I ensure ANSI-compliance in the same query?


Solution

  • Assuming that the value is passed to your query in a @value parameter, you can do it like this:

    SELECT *
    FROM MyTable
    WHERE (@value IS NOT NULL AND parameter = @value) -- Or simply parameter = @value
       OR (@value IS NULL AND parameter IS NULL)