从匿名块调用存储过程

时间:2014-06-01 07:26:15

标签: oracle stored-procedures plsql

我在本地机器上的Oracle 11gr2数据库上用sql developer编写的plsql存储过程读取结果有问题。

这是我的表:

create table MY_TEST_TABLE
(employee_id    NUMBER(6)
,first_name     VARCHAR2(20)
,last_name      VARCHAR2(25) 
,email          VARCHAR2(25) 
,phone_number   VARCHAR2(20));

这是程序声明:

create or replace PACKAGE TEST_PACKAGE AS 
procedure test_procedure (i_id in number,
                          o_data out sys_refcursor);
END TEST_PACKAGE;

这是正文:

create or replace PACKAGE BODY TEST_PACKAGE AS
  procedure test_procedure (i_id in number,
                        o_data out sys_refcursor) AS
  BEGIN
    open o_data for
      select  employee_id,
          first_name,
          last_name,
          email,
          phone_number
      from my_test_table
      where EMPLOYEE_ID = i_id;     
    close o_data;
  END test_procedure;
END TEST_PACKAGE;

这是匿名阻止调用:

SET serveroutput on
DECLARE
  in_id number; 
  my_cursor sys_refcursor;
  current_record my_test_table%ROWTYPE;
BEGIN
  in_id := 1;
  test_package.test_procedure(in_id, my_cursor);
  open my_cursor;
  LOOP
    FETCH my_cursor INTO current_record;
      EXIT WHEN my_cursor%NOTFOUND;
    dbms_output.put_line(' - out - ' || current_record.employee_id);
  END LOOP;
END;

我收到错误:

Error starting at line : 2 in command -
DECLARE
  in_id number; 
  my_cursor sys_refcursor;
  current_record my_test_table%ROWTYPE;
BEGIN
  in_id := 1;
  test_package.test_procedure(in_id, my_cursor);
  open my_cursor;
  LOOP
    FETCH my_cursor INTO current_record;
      EXIT WHEN my_cursor%NOTFOUND;
    dbms_output.put_line(' - out - ' || current_record.employee_id);
  END LOOP;
END;
Error report -
ORA-06550: line 8, column 5:
PLS-00382: expression is of wrong type
ORA-06550: line 8, column 5:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

有人可以解释什么是错的吗? TNX!

1 个答案:

答案 0 :(得分:7)

光标在过程中打开,因此您不需要也不能直接在匿名块中打开它。好吧,它应该是开放的,但你也在程序中关闭它。从过程中删除close,从块中删除open

create or replace PACKAGE BODY TEST_PACKAGE AS
  procedure test_procedure (i_id in number,
                        o_data out sys_refcursor) AS
  BEGIN
    open o_data for
      select  employee_id,
          first_name,
          last_name,
          email,
          phone_number
      from my_test_table
      where EMPLOYEE_ID = i_id;     
--    close o_data;
  END test_procedure;
END TEST_PACKAGE;
/

DECLARE
  in_id number; 
  my_cursor sys_refcursor;
  current_record my_test_table%ROWTYPE;
BEGIN
  in_id := 1;
  test_package.test_procedure(in_id, my_cursor);
--  open my_cursor;
  LOOP
    FETCH my_cursor INTO current_record;
      EXIT WHEN my_cursor%NOTFOUND;
    dbms_output.put_line(' - out - ' || current_record.employee_id);
  END LOOP;
END;
/

SQL Fiddle - 只需添加数据......