检查 Oracle SQL DECODE 函数结果是否为 0

Checking the Oracle SQL DECODE function result against 0

我在看一些旧的 PL/SQL 代码,我有很多这样写的 DECODE 函数:

DECODE(value_1, value_2, 1, 0) = 0

现在,我知道这些解码器在 value_1value_2 之间进行比较,它们 return true 或 false 基于比较的结果。但是,出于对编码的热爱,有人可以告诉我 = 0 部分背后的逻辑是什么吗?为什么有必要对照 0 检查 return 值?

  • 如果value_1 = value_2,则解码returns1
  • 否则,returns0

因此,整个表达式检查 value_1 是否与 value_2 不同,然后 - 我推测 - 做了 某事 .

如果它是 PL/SQL 的一部分,您可以将其重写为

if value_1 <> value_2 then...

一些示例:

SQL> declare
  2    value_1 number := 5;
  3    value_2 number := 1;
  4  begin
  5    decode(value_1, value_2, 1, 0) = 0
  6  end;
  7  /
  decode(value_1, value_2, 1, 0) = 0
                                 *
ERROR at line 5:
ORA-06550: line 5, column 34:
PLS-00103: Encountered the symbol "=" when expecting one of the following:
:= . ( % ;


SQL> declare
  2    value_1 number := 5;
  3    value_2 number := 1;
  4  begin
  5    decode(value_1, value_2, 1, 0) = 0;
  6  end;
  7  /
  decode(value_1, value_2, 1, 0) = 0;
                                 *
ERROR at line 5:
ORA-06550: line 5, column 34:
PLS-00103: Encountered the symbol "=" when expecting one of the following:
:= . ( % ;
The symbol ":= was inserted before "=" to continue.


SQL> declare
  2    value_1 number := 5;
  3    value_2 number := 1;
  4  begin
  5    if decode(value_1, value_2, 1, 0) = 0 then
  6       null;
  7    end if;
  8  end;
  9  /
  if decode(value_1, value_2, 1, 0) = 0 then
     *
ERROR at line 5:
ORA-06550: line 5, column 6:
PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL statement only
ORA-06550: line 5, column 3:
PL/SQL: Statement ignored


SQL> declare
  2    value_1 number := 5;
  3    value_2 number := 1;
  4  begin
  5    case when decode(value_1, value_2, 1, 0) = 0 then
  6         null;
  7    end case;
  8  end;
  9  /
  case when decode(value_1, value_2, 1, 0) = 0 then
            *
ERROR at line 5:
ORA-06550: line 5, column 13:
PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL statement only
ORA-06550: line 5, column 3:
PL/SQL: Statement ignored


SQL> declare
  2    value_1 number := 5;
  3    value_2 number := 1;
  4    l_decode_result number;
  5  begin
  6    select decode(value_1, value_2, 1, 0)
  7      into l_decode_result
  8      from dual;
  9  end;
 10  /

PL/SQL procedure successfully completed.

SQL>