如何以及何时在 oracle 中使用 sys_refcursor

Ale*_*das 10 oracle oracle-11g

有人可以给我一个关于如何以及何时使用 sys_refcursor 的小解释吗?

Chr*_*xon 10

游标是指向查询结果集的指针。通过返回 a ,sys_refcursor您允许客户端根据需要从查询中获取尽可能多或少的行。在有状态应用程序中,这可用于翻阅结果。

与编写返回数组的 PL/SQL 函数相比,游标可以提供更大的灵活性,因为它完全取决于客户端要获取多少行以及何时停止。也就是说,我没有发现很多情况下这种额外的灵活性是有用的。

值得注意的是,sys_refcursor是弱类型的,因此您可以返回指向查询的指针,这些查询不仅具有不同的 from 或 where 子句,而且还有不同数量和类型的列。或者,您可以使用强类型游标,其中结果集中的列是固定的。

这使您能够编写返回不同查询的函数,如下所示:

create function get_data ( type varchar2 ) return sys_refcursor as
  ret_cur sys_refcursor;
begin

  if type = 'EMP' then
    open ret_cur for select * from emp;
  elsif type = 'DEPT' then
    open ret_cur for select * from dept;
  end if;

  return ret_cur;
end;
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用sys_refcursor上述方法创建通用的“打开查询”函数,那么您可能做错了!

  • @JohnnyWu “给我任何东西”功能将更难管理。您如何进行测试以确保在所有情况下都获得正确的结果?安全呢?如果您正在构建一个框架,这可能是必要的。但是对于一般的业务逻辑,最好有单独的`get_emps` 和`get_depts` 函数 (2认同)