在ORACLE的select语句中调用PL/SQL中的函数

5 oracle plsql

这是我的PL/SQL函数部分.我试图在select语句中使用该函数.例如,我们可以编写一个类似的查询select count(column_name) from table_name.这里count是一个函数.我想使用我自己的这样的功能.我尝试过不同的方法(使用PL/SQL函数之外的函数,在PL/SQL函数中).但是PLS-00231:function 'GET_ANNUAL_COMP' may not be used in SQL当它在PL/SQL函数内部使用时抛出一个错误,并且当在PL/SQL函数ORA-00904 invalid identifier之外使用时抛出它.

我正在使用oracle 11g.

declare
em_sal number(20);
em_comm employees.commission_pct%type; 
annual_salary number(10,4);

function get_annual_comp(sal in number, comm in number)
return number is
begin
return (sal*12 + comm*12);
end;
begin
select salary into em_sal from employees where employee_id=149;
select commission_pct into em_comm from employees where employee_id=149;

annual_salary := get_annual_comp(em_sal,em_comm);

dbms_output.put_line('total salary '|| annual_salary);

select get_annual_comp(salary,commission_pct) from employees where department_id=90;
end;
/
Run Code Online (Sandbox Code Playgroud)

Pat*_*con 7

在适当的模式(将运行匿名块的sames模式)中编译函数,如下所示:

CREATE OR REPLACE FUNCTION GET_ANNUAL_COMP(
    sal  IN NUMBER,
    comm IN NUMBER)
  RETURN NUMBER
IS
BEGIN
  RETURN (sal*12 + comm*12);
END;
Run Code Online (Sandbox Code Playgroud)

使用与函数相同的模式,运行匿名块:

DECLARE
  em_sal NUMBER(20);
  em_comm employees.commission_pct%type;
  annual_salary NUMBER(10,4);
BEGIN
  SELECT salary INTO em_sal FROM employees WHERE employee_id=149;
  SELECT commission_pct INTO em_comm FROM employees WHERE employee_id=149;
  annual_salary := get_annual_comp(em_sal,em_comm);
  dbms_output.put_line('total salary '|| annual_salary);
  SELECT SUM(get_annual_comp(salary,commission_pct)) into annual_salary
  FROM employees
  WHERE department_id=90;
  dbms_output.put_line('department annual salary '|| annual_salary);
END;
/
Run Code Online (Sandbox Code Playgroud)