替代 DECODE 类似函数,用于 PLSQL 过程中的 elsif 语句



我正在尝试使用一个条件elsif需要使用解码之类的东西,以便条件为真并进行插入。我正在一个程序和条件下这样做,就像

elsif ((v_DIVIDEND/Divisor)-1 < ABS(0.2)) then 
    insert into table(Divisor,b,c) values(Dividend,y,z);

除数不为零时,它工作正常,但当除数为零时,它失败。我想排除除数中的零,就像elsif内的另一个嵌套 if 条件或解码之类的东西一样。我尝试了另一种if但语法似乎错误。使用 Decode 表示它只能在 SQL 语句中使用。任何建议,请...

您还可以处理"除数等于零"异常,并在发生错误时进行插入,请参阅处理"除数等于零"异常的示例代码,

示例 1:此示例定义divisor_equal_to_zero异常

DECLARE
    divisor_equal_to_zero EXCEPTION;
    PRAGMA EXCEPTION_INIT(divisor_equal_to_zero, -1476);
    v_divisor NUMBER := 0;
    v_quotient NUMBER;
BEGIN
    v_quotient := 1/v_divisor;
    DBMS_OUTPUT.PUT_LINE('Print A: '||v_quotient);
EXCEPTION
    WHEN divisor_equal_to_zero THEN
        v_divisor := 1;
        v_quotient := 1/v_divisor;
        DBMS_OUTPUT.PUT_LINE('Print B: '||v_quotient);
        --you can put the insert statement here
END;
/

示例 2:此示例使用预定义的ZERO_DIVIDE异常

DECLARE
    v_divisor NUMBER := 0;
    v_quotient NUMBER;
BEGIN
    v_quotient := 1/v_divisor;
    DBMS_OUTPUT.PUT_LINE('Print A: '||v_quotient);
EXCEPTION
    WHEN ZERO_DIVIDE THEN
        v_divisor := 1;
        v_quotient := 1/v_divisor;
        DBMS_OUTPUT.PUT_LINE('Print B: '||v_quotient);
        --you can put the insert statement here
END;
/

好吧,根据除数 = 0 时你想要得到的结果(即的东西或的东西(,你可以使用这样的东西:

对于小结果(除以 1E99(:

case when divisor = 0 then 1E99 else divisor end

对于较大的结果(除以 1E-99(

case when divisor = 0 then 1E-99 else divisor end

由于您无法使用解码:没错,它只能在 SELECT 语句中使用。这意味着你应该重写你的代码,把所有的东西都放到SELECT中(这可能是一个坏主意(。所以 - 试试 CASE。

也许您可以添加这样的条件来检查Divisor是否为零。

elsif ( Divisor !=0 )  and  ((v_DIVIDEND/Divisor)-1 < ABS(0.2))
THEN 
insert into table(Divisor,b,c) values(Dividend,y,z)
elsif Divisor = 0 
THEN
insert into table(Divisor,b,c) values(?,?,?);

你可以试试nullif

declare 
    divisor constant integer := 0;
    result number;
begin
    result := 100 / nullif(divisor,0);
end;

这里divisor如果值为0,则用 null 替换,给出result为 null。

最新更新