Search code examples
sqlsql-servert-sql

WHERE clause that needs to be NULL or NOT NULL


I need help coding for the where clause in a stored procedure passing in these input parameters:

DECLARE @UID_CUSTOMER           int = 7
    ,   @BOOL_HAS_DEFECT        bit = 0
    ,   @BOOL_HAS_INSPECTION    bit = 0
    ,   @DTTM_TRIP_START        datetime = '2024-01-01'
    ,   @DTTM_TRIP_END          datetime = '2024-06-01'
    ;

In the T-SQL query, I would use this WHERE clause:

WHERE ... other conditions ...
  AND (PTI.UID_PTINSPECTION IS NOT NULL)
  AND (TMD.UID_TMDEFECT IS NOT NULL);

However, I want to use the inbound parameter @BOOL_HAS_INSPECTION as here:

  AND (PTI.UID_PTINSPECTION (CASE WHEN @BOOL_HAS_INSPECTION = 1 
                        THEN (IS NOT NULL)
                        ELSE (IS NULL) END))

This code fragment is invalid.

Question: how can I use the @BOOL_HAS_INSPECTION to properly specify IS NOT NULL and/or IS NULL?


Solution

  • This will work, but there may be a more concise way.

    WHERE ... AND
    ( (@BOOL_HAS_INSPECTION = 1 AND PTI.UID_PTINSPECTION IS NOT NULL)
    OR (@BOOL_HAS_INSPECTION = 0 AND PTI.UID_PTINSPECTION IS NULL) )