繁体   English   中英

在Oracle 12c中使用IF / ELSE子句添加内联函数

[英]Add inline function with IF/ELSE clause in Oracle 12c

我有表A。如果我使用内联函数进行查询

with function f(n number) return varchar2 as
   begin
    return 'const string';
   end;
select id, val, count, f(count) as value from A;

结果如下:

    ID         VAL                       COUNT VALUE
    ---------- -------------------- ---------- ---------------
     1         car                           4 const string
     2         building                     15 const string

但是如果我尝试使功能更复杂

with function f(n number)
   return varchar2 as
   begin
    IF n < 5 THEN
            return 'small';
        ELSIF n < 50 THEN
            return 'normal';
        ELSE 
            return 'big';
        END IF;
    end;
select id, val, count, f(count) as value from A;

出现错误信息:

with function f(n number)
              *
ERROR at line 1:
ORA-00905: missing keyword

这是什么问题 我对命令使用正确的语法吗?

if语句缺少thenelsif子句条件,因此缺少关键字错误指向功能f 此外,解决此错误后,您可能会得到ORA-00933: SQL command not properly ended指向最后一个分号。 有趣的是,“;” 当WITH子句中包含PL / SQL声明时,似乎不能作为SQL语句的终止符。 如果我们尝试单独使用它,SQL * Plus将等待输入更多文本。 因此,您必须在新行上以/结束。 即使在《 SQL参考手册》中的示例中,也使用了;的组合; / 这是我在PL / SQL Developer 11中测试过的示例:

WITH
 FUNCTION f(n number) return varchar2 IS
   begin
     if n<5 then 
       return 'small';
     elsif (n>5 AND n<50) then
       return 'medium';
     else 
       return 'big';
      end if;     
   end;  
select f(25) from dual
/

输出:

F(25)
medium

编辑:另外,在函数定义中将AS更改为IS

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM