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

來源:互聯網
上載者:User

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轉換輸出。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.