[英]Oracle CASE statement?
I have a stored proc. 我有一个存储过程。 where i am passing a boolean value eg IS_ELIGIBLE. 我在哪里传递一个布尔值,例如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. 问题是因为IS_ELIGIBLE不是TABLE_NAME中的列之一,查询错误输出。 I can write the same query using if..else ie. 我可以使用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. 我知道我可以创建具有select语句的函数,这样我就不必重复两次了。 But i was just curious if it can be done without doing if..else or creating new function? 但我只是好奇是否可以在不执行if..else或创建新功能的情况下完成? 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). 问题不在于IS_ELIGIBLE不是表中的列,而是它是一个布尔值而SQL无法处理布尔值(我知道,不要问)。 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. Boolean不是SQL引擎的有效类型。
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. 但是,如果这确实是您的SProc的参数,那么对于任何给定的调用它都是一个常数。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.