Oracle存储过程:返回结果集和输出参数

Sun*_*day 2 oracle stored-procedures

Oracle存储过程具有OUT参数并返回结果集,例如

create or replace procedure foo(empId IN NUMBER, maxSalary OUT NUMBER) AS BEGIN
    select * from Employee e where e.id >=empId;
    select max(salary) into maxSalary from Employee;
END;
Run Code Online (Sandbox Code Playgroud)

错误:

PLS-00428: an INTO clause is expected in this SELECT statement
Run Code Online (Sandbox Code Playgroud)

Mysql存储过程可以返回结果集和输出参数.如何为oracle db做到这一点?

Kau*_*yak 5

在Oracle中,如果没有INTO子句,则无法运行直接select语句.

如果您使用的是Oracle 12c及更高版本,则可以使用REF CURSORDBMS_SQL.RETURN_RESULT

create or replace procedure foo(empId IN NUMBER, maxSalary OUT NUMBER) AS
q SYS_REFCURSOR;
 BEGIN
    OPEN q FOR select * from Employee e where e.id >=empId;
     DBMS_SQL.return_result (q); -- This will display the result
    select max(salary) into maxSalary from Employee;
END;
Run Code Online (Sandbox Code Playgroud)

对于以前的版本(11g,10g),您可以将a REF CURSOR作为OUT参数传递,并sqlplus通过以脚本形式运行来打印或TOAD.

create or replace procedure foo(empId IN NUMBER, maxSalary OUT NUMBER,
   q OUT SYS_REFCURSOR) AS

     BEGIN
        OPEN q FOR select * from Employee e where e.id >=empId;
        select max(salary) into maxSalary from Employee;
    END;
Run Code Online (Sandbox Code Playgroud)

在调用过程之前定义绑定变量.

VARIABLE v_empID NUMBER
VARIABLE v_maxsalary NUMBER
VARIABLE v_q REFCURSOR

EXEC :v_empID := 101
EXEC foo(:v_empID,:v_maxsalary,:v_q ) 
PRINT v_q -- This will display the result from the query.
Run Code Online (Sandbox Code Playgroud)