我可以将显式游标传递给要在FOR循环中使用的函数/过程吗? [英] Can I pass an explicit cursor to a function/procedure for use in FOR loop?

查看:90
本文介绍了我可以将显式游标传递给要在FOR循环中使用的函数/过程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过程,可以对游标返回的所有记录进行一些计算.看起来像这样:

I have a procedure that performs some calculations on all records returned by a cursor. It looks a bit like this:

PROCEDURE do_calc(id table.id_column%TYPE)
IS
  CURSOR c IS
    SELECT col1, col2, col3
      FROM table
     WHERE ...;
BEGIN
  FOR r IN c LOOP
    -- do some complicated calculations using r.col1, r.col2, r.col3 etc.
  END LOOP;
END;

现在,我需要对来自不同表的一组不同记录执行完全相同的计算.但是,它们具有与上面示例中相同的形状".

Now I have the case where I need to perform the exact same calculation on a different set of records that come from a different table. However, these have the same "shape" as in the above in example.

是否可以编写如下所示的过程:

Is it possible to write a procedure that looks like this:

PROCEDURE do_calc2(c some_cursor_type)
IS
BEGIN
  FOR r IN c LOOP
    -- do the calc, knowing we have r.col1, r.col2, r.col3, etc.
  END LOOP;
END;

我了解SYS_REFCURSOR,但是我想知道是否可以使用更方便的FOR ... LOOP语法和隐式记录类型.

I know about SYS_REFCURSOR, but I was wondering if it was possible to use the much more convenient FOR ... LOOP syntax and implicit record type.

推荐答案

创建一个包.

将光标声明为包变量.

使用%rowtype设置功能参数类型.

Use %rowtype to set function parameter type.

create or replace package test is
  cursor c is select 1 as one, 2 as two from dual;

  procedure test1;
  function test2(test_record c%ROWTYPE) return number;

end test;


create or replace package body test is
  procedure test1 is    
  begin
    for r in c loop      
      dbms_output.put_line(test2(r));
    end loop;
  end;

  function test2(test_record c%ROWTYPE) return number is
    l_summ number;
  begin
    l_summ := test_record.one + test_record.two;
    return l_summ;
  end;
end test;

这篇关于我可以将显式游标传递给要在FOR循环中使用的函数/过程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆