在存储过程中声明SYS_REFCURSOR和ROWTYPE

时间:2014-05-20 14:25:49

标签: sql oracle stored-procedures plsql

所以我有一个存储过程ONE

create or replace PROCEDURE ONE
(
   A in number
   B in number
   ...
   ZZ out SYS_REFCURSOR
) IS
  SOME_OTHER_STUFF
BEGIN
   ...
END

这将返回一个sys_refcursor,其中包含我需要的一些数据。然后我有一个存储过程TWO

create or replace PROCEDURE TWO
(
   A in number
   B in number
   ...
   ZZ out SYS_REFCURSOR
) IS
     Count_Records Sys_Refcursor;
     l_rec Count_Records%rowtype;
BEGIN
    /* get some data from the ONE stored procedure to use on this procedure*/
    ONE(A,B,...Count_Records)

    Loop
       fetch count_records into l_rec;
       Exit When count_records%Notfound;
       If  l_rec.TT_RAW > MAX_RECORDS  Then
         Raise To_Many_Results;
       End If;
    End Loop;

END

当我尝试声明rowtype l_rec Count_Records%rowtype;

时,我收到错误消息

如何声明此变量?问题是TT_RAW这是我想要获取的列是一个SUM,并且游标没有映射到任何包含大量计算的表。

由于

2 个答案:

答案 0 :(得分:6)

sys_refcursor的重点是它是动态定义的。另一方面,rowtype声明必须是静态的(如果不是,编译器无法判断从中引用的字段是否有效)。这是一个用例的定义,您应该定义自己的强类型引用游标,而不是使用sys_refcursor

以下是一个非常简单的例子:

CREATE OR REPLACE PACKAGE BODY rc_example IS
   PROCEDURE two (a IN NUMBER, b IN NUMBER);
END rc_example;
/

CREATE OR REPLACE PACKAGE BODY rc_example IS
   TYPE one_record IS RECORD (FIRST_VALUE VARCHAR2 (10));

   TYPE one_cursor IS REF CURSOR
      RETURN one_record;

   --Could alternately be declared using a table's rowtype:
   --TYPE one_cursor is ref cursor return some_table%rowtype;

   PROCEDURE one (a IN NUMBER, b IN NUMBER, zz OUT one_cursor) IS
   BEGIN
      OPEN zz FOR SELECT 'test' FROM DUAL;
   END one;

   PROCEDURE two (a IN NUMBER, b IN NUMBER) IS
      count_records SYS_REFCURSOR;
      l_rec count_records%ROWTYPE;
   BEGIN
      one (a, b, count_records);

      LOOP
         FETCH count_records INTO l_rec;

         DBMS_OUTPUT.put_line (l_rec.FIRST_VALUE);
         EXIT WHEN count_records%NOTFOUND;
      END LOOP;
   END two;
END rc_example;
/

答案 1 :(得分:1)

您可以改为获取变量列表,或创建自己的记录类型:

...
fetch count_records into v_field1, v_field2, v_field3
...