简体   繁体   中英

Dynamic where clause based on variable

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 = NULL as 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:

WHERE @option1 = 'False' OR d IS NULL

If you prefer to use a CASE statement for some reason, you can write it like this:

WHERE 1 = CASE WHEN @option1 = 'False' THEN 1 
               WHEN @option1 = 'True' AND d IS NULL THEN 1 
               ELSE 0 
          END

This:

UPDATE: PinnyM has straightened me out on this. I am leaving my embarrassing logically flawed argument here for the education of the masses. The solution I propose below after "Try this" is certainly still valid, but PinnyM's solutions is by far more elegant and should be used.

WHERE @option1 = 'False' OR d IS NULL

Will always return all the results given his current select statement (assuming @Option1 is simply a flag parameter passed in).

Try this:

SELECT a, b, c, d
WHERE 
    -- Returns only rows where d is null (if @Option1 is True)
    (@Option1 = 'True' AND d IS NULL) 
    OR
     -- returns all the rows (if @Option1 is False)
    (@Option1 = 'False')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM