1. 程式人生 > >Oracle sql語句中不支援boolean型別(decode&case)

Oracle sql語句中不支援boolean型別(decode&case)

Oracle sql語句中不支援boolean型別(decode&case)

版本資訊:
SQL> select * from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE    11.1.0.7.0      Production
TNS for Linux: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - Production

假設我們現在想知道1>0是否為真:

直接查,不行!
SQL> select 1>0 from dual;
select 1>0 from dual
        *
ERROR at line 1:
ORA-00923: FROM keyword not found where expected

用decode轉,還是不行!
SQL> select decode(1>0,true,'true','false') from dual;
select decode(1>0,true,'true','false') from dual
               *
ERROR at line 1:
ORA-00907: missing right parenthesis

用case轉,依舊不行!
SQL> select case 1>0 when true then 'true' else 'false' end from dual;
select case 1>0 when true then 'true' else 'false' end from dual
            *
ERROR at line 1:
ORA-00923: FROM keyword not found where expected

原因在於sql不支援boolean型別(手頭沒有其他庫,不知道mysql和sqlserver是否支援):
SQL> create or replace function is_true return boolean
is
begin
return true;
end;
/

Function created.

SQL> select is_true from dual;
select is_true from dual
       *
ERROR at line 1:
ORA-06552: PL/SQL: Statement ignored
ORA-06553: PLS-382: expression is of wrong type

直接放sql語句中行不通,試著放到fuction裡:
decode還是出錯:
SQL> CREATE OR REPLACE FUNCTION is1gt0
  RETURN VARCHAR2
IS
BEGIN
  RETURN DECODE (1 > 0, TRUE, 'true', 'false');
END;
/

Warning: Function created with compilation errors.

SQL> show err;
Errors for FUNCTION IS1GT0:

LINE/COL ERROR
-------- -----------------------------------------------------------------
5/3      PL/SQL: Statement ignored
5/10     PLS-00306: wrong number or types of arguments in call to 'DECODE'
SQL>

case完美通過:
SQL> CREATE OR REPLACE FUNCTION is1gt0
  RETURN VARCHAR2
IS
BEGIN
  RETURN CASE 1 > 0
    WHEN TRUE
      THEN 'true'
    ELSE 'false'
  END;
END;
/

Function created.

SQL> show err;
No errors.
SQL> select is1gt0 from dual;

IS1GT0
--------------------------------------------------------------------------------
true

SQL>


小結:
1. Oracle sql語句中不支援boolean型別;
2. decode是oracle獨有的;而case是標準sql,mysql和sqlserver也可以使用,而且case還能把boolean轉換輸出。


REF:
1.Decode function to Oracle 7
http://www.groupsrv.com/computers/about56979.html