Question

I know i could probably accomplish this by easily putting two whole statements in a CASE statement itself, but i'm new to SQL and trying to learn to write this the most efficient and intelligent way without duplicating any logic, and so i figure maybe there is a way i can turn a where condition line on or off basically.

I have the following statement(which doesn't work btw, missing a keyword it says):

      OPEN O_CURSOR FOR
       SELECT S.STORE_NO_4_DIGIT AS STORE_NO, S.STORE_NAME
         FROM RFS.RF_STORE S
        WHERE S.TYPE_CODE != 'W'
        AND
            CASE I_CAN_BE_CLOSED
                WHEN 0 THEN
                S.CLOSE_DATE IS NULL
            END                
     ORDER BY S.STORE_NO_4_DIGIT;

There is two cases based on the input variable I_CAN_BE_CLOSED, values 0 or 1.

In one case i want to allow it to return stores with only NULL CLOSE_DATES, and in the other case i want it to return either(both closing and non-closing stores).

Was it helpful?

Solution

CASE expression cannot return boolean in Oracle SQL. This should be equivalent, provided that I_CAN_BE_CLOSED is never NULL:

  OPEN O_CURSOR FOR
   SELECT S.STORE_NO_4_DIGIT AS STORE_NO, S.STORE_NAME
     FROM RFS.RF_STORE S
    WHERE S.TYPE_CODE != 'W'
    AND (I_CAN_BE_CLOSED != 0 OR S.CLOSE_DATE IS NULL)
 ORDER BY S.STORE_NO_4_DIGIT;

Edit:

In fact both answers given here are correct... Easiest way to verify is to write down every case in a truth-false table:

I_CAN_BE_CLOSED  S.CLOSE_DATE  [1]                      [2]   
0                 NULL          FALSE OR TRUE = TRUE    (TRUE AND TRUE) OR FALSE = TRUE
0                 NOT NULL      FALSE OR FALSE = FALSE  (TRUE AND FALSE) OR FALSE = FALSE
1                 NULL          TRUE OR TRUE = TRUE     (FALSE AND TRUE) OR TRUE = TRUE
1                 NULL          TRUE OR FALSE = TRUE    (FALSE AND FALSE) OR TRUE = TRUE

[1] == "I_CAN_BE_CLOSED != 0 OR S.CLOSE_DATE IS NULL"
[2] == "((i_can_be_closed = 0 and s.close_date IS NULL) or (i_can_be_closed = 1))"

OTHER TIPS

It sounds like you just want to OR together a couple of predicates

AND ((i_can_be_closed = 0 and s.close_date IS NULL) or
     (i_can_be_closed = 1))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top