简体   繁体   中英

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

I have table A. If I make a query with inline function

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

the result will be following:

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

But if I try to make the function more complicated

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;

an error message appears:

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

What's the problem here? Do I use right syntax for the command?

Your if statement is missing a then after the elsif condition clause, hence the missing keyword error pointing to function f . Also, after you fix this error you may get a ORA-00933: SQL command not properly ended pointing to the last semi-colon. Interestingly, the ";" does not seem to work as a terminator to the SQL statement when the PL/SQL declaration is included in the WITH clause. If we attempt to use it on its own, SQL*Plus waits for more text to be entered. So you have to end it with a / on a new line. Even in the example in SQL Reference manual uses a combination of ; and / . Here is my example I tested in 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
/

Output:

F(25)
medium

EDIT: Also, change your AS to IS in your function definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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