简体   繁体   中英

Oracle SQL CASE expression in WHERE clause only when conditions are met

Cant quite figure this one out, i have a set of conditions that i want to be met only if a value is in a field.

So if the Status is complete i want to have three where clause's, if the status doesn't equal complete then i don't want any where clause.

Code

SELECT *
FROM mytable
WHERE CASE WHEN Status = 'Complete'
           THEN (included = 0 OR excluded = 0 OR number IS NOT NULL)
           ELSE *Do nothing*

It is usually simple to only use boolean expressions in the WHERE . So:

WHERE (Status <> 'Complete') OR 
      (included = 0 OR excluded = 0 OR number IS NOT NULL)

If Status could be NULL :

WHERE (Status <> 'Complete' OR Status IS NULL) OR 
      (included = 0 OR excluded = 0 OR number IS NOT NULL)

You can translate the natural language in SQL, then, if possible, reformulate.

SELECT *
FROM mytable
WHERE (Status = 'Complete' and (included = 0 OR excluded = 0 OR number IS NOT NULL)) 
     or status <> 'Complete'
     or status IS NULL;

It doesn't look like you really need a CASE statement, just use it like this:

SELECT *
FROM mytable
WHERE where (Status = 'Complete' and (included = 0 OR excluded = 0 OR number IS NOT NULL)) or (*Your do nothing*)

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