存储过程中的编译错误 (Oracle SQL)

Compilation error in Stored Procedure (Oracle SQL)

create or replace function getAvg(id1 IN number, id2 IN number) return number as
sal1 number;
sal2 number;
avg number;
BEGIN
    select esal into sal1 from employees where eno = id1;
    select esal into sal2 from employees where eno = id2;
    avg := (sal1+sal2)/2;
    return avg;
END;
/

当我尝试编译以上代码时,出现编译错误并显示以下消息:

Warning: Function created with compilation errors.

但是当我将 return 之后的 avg 替换为 (sal1+sal2)/2 时,它编译成功。

那是坏习惯:永远不要使用保留字或关键字命名您自己的对象、变量。 avg 是内置函数;重命名变量:

SQL> create or replace function getAvg(id1 IN number, id2 IN number)
  2    return number
  3  as
  4    sal1 number;
  5    sal2 number;
  6    l_avg number;
  7  BEGIN
  8      select esal into sal1 from employees where eno = id1;
  9      select esal into sal2 from employees where eno = id2;
 10      l_avg := (sal1+sal2)/2;
 11      return l_avg;
 12  END;
 13  /

Function created.

SQL> select * from employees;

       ENO       ESAL
---------- ----------
         1        100
         2        200

SQL> select getavg(1, 2) from dual;

GETAVG(1,2)
-----------
        150

SQL>