简体   繁体   中英

Oracle CASE statement?

I have a stored proc. where i am passing a boolean value eg IS_ELIGIBLE. Now i want to be able to write query something like this:

SELECT col1,
       CASE 
          WHEN IS_ELIGIBLE THEN col2 * 100
       ELSE
          col2 * 50
       END
         INTO OUT_COL1, OUT_SCORE
FROM TABLE_NAME

The problem is since IS_ELIGIBLE is not one of the column in TABLE_NAME, the query errors out. I can write the same query using if..else ie.

IF IS_ELIGIBLE
   SELECT col1, col2 * 100
ELSE
   SELECT col1, col2 * 50
END

But i will be repeating select statement twice. I know i can create the function to have that select statement so that i don't have to repeat twice. But i was just curious if it can be done without doing if..else or creating new function? Thanks.

The problem is not that IS_ELIGIBLE isn't a column in the table, but that it is a Boolean and SQL cannot handle Boolean values (I know, don't ask). So you need to introduce another variable something like this:

IS_ELIGIBLE_NUM NUMBER := CASE WHEN IS_ELIGIBLE THEN 1 ELSE 0 END;
..
SELECT col1,
   CASE 
      WHEN IS_ELIGIBLE_NUM = 1 THEN col2 * 100
   ELSE
      col2 * 50
   END
     INTO OUT_COL1, OUT_SCORE
FROM TABLE_NAME

Boolean is not a valid type for the SQL engine.
You would have to use a temporary variable of a supported type for that.

However, if this really is a parameter to your SProc, then it is kinda constant with any given call.

So, why not do it like so:

  someVarForCol2 TABLE_NAME.col2%type;
begin
  SELECT col1, col2
  INTO OUT_COL1, someVarForCol2
  FROM TABLE_NAME;

  OUT_SCORE := CASE WHEN IS_ELIGIBLE THEN someVarForCol2 * 100 ELSE someVarForCol2 * 50 END;

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