开发者

Oracle CASE statement?

开发者 https://www.devze.com 2023-03-12 23:42 出处:网络
I have a stored proc. where i am passing a boolean value e.g. IS_ELIGIBLE. Now i want to be able to write query something like this:

I have a stored proc. where i am passing a boolean value e.g. 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 i开发者_开发技巧f..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;
0

精彩评论

暂无评论...
验证码 换一张
取 消