I am working on a select statement in SQL and am running into issues trying to create a where clause that includes a case statement or an if else statement. I want to select records based on the value of a variable. If the variable is ‘True’ then only return records from the select statement where a column is null. If the variable is not ‘True’ then return all records regardless if that columns is null.
Any tips on how to do this?
Below is a simple example of what i am trying to do:
declare @option1 as varchar(5)
--This can be True or False so to test i just put the Set option below
set @option1 = 'True'
Select a,b,c,d...
from ...
where d = case when @option1 = 'True' then NULL End
This is the part where i do not know what to do. I only need to filter out the records if the variable is ‘True’ so not sure what to put in the else section of the case.
You can’t test for
d = NULLas your CASE statement does because that will always return false since NULL is not equal to NULL (unless you set ANSI_NULLS to ‘off’).The simplest thing to do would be to change the WHERE clause to this:
If you prefer to use a CASE statement for some reason, you can write it like this: