使用SQL语句的Oracle引用游标



REF CURSOR在Oracle中的作用是什么?为什么我们需要SQL语句,即

OPEN c2 FOR sqlstmt USING c3_rec.id;

这是光标代码,请帮忙。

TYPE cur_ref IS REF CURSOR;
    c2 cur_ref;
    sqlstmt VARCHAR2(2000);
    total       INTEGER;

sqlstmt:='SELECT COUNT(*) total FROM "'||owner||'".'||table||' WHERE '||:NEW.cname||' = :1';
OPEN c1 FOR sqlstmt USING :NEW.min;

BEGIN
        OPEN c2 FOR sqlstmt USING c3_rec.id;
        FETCH c2 INTO total;
        CLOSE c2;
    EXCEPTION
        WHEN others THEN
            error(1006, id: %s %s raised by: %s')

REF CURSOR在Oracle中的作用是什么?为什么我们需要SQL语句

REF Cursor的基本用途是,它可以在服务器上打开,并作为一个单元传递给客户端,而不是一次获取一行。它可以作为参数传递给其他程序单元。

现在进入SQL语句,在执行时它将获取所需的行。ref游标保存SQL语句返回的记录集。

因此,REF Cursor是一种保存游标值的数据类型,与VARCHAR2变量保存字符串值的方式相同。

是的,Oracle 9i引入了预定义的SYS_REFCURSOR,以避免您自己的REF CURSOR类型。但是,它是一个弱ref游标类型。定义良好的井游标被认为是强引用游标类型。

你会在$ORACLE_HOME/rdbms/admin/stdspec.sql:中发现一些有趣的东西

/* Adding a generic weak ref cursor type */
type sys_refcursor is ref cursor;

简而言之,两者都是一样的。

所以,在你的情况下,这个:

TYPE cur_ref IS REF CURSOR;
c2 cur_ref;

可以写成:

c2 SYS_REFCURSOR;

使用REF CURSOR可以使代码更加灵活,例如:

declare
  type t_c1 is ref cursor;
  c1 t_c1;
  l_count number(10);
  l_object_type varchar2(50);
begin
  l_object_type := 'TABLE';
  open c1 for 'SELECT count(*) from user_objects where object_type = :object_type' using l_object_type;
  fetch c1 into l_count;
  close c1;
  DBMS_OUTPUT.put_line('You have ' || l_count || ' tables');
  l_object_type := 'VIEW';
  open c1 for 'SELECT count(*) from user_objects where object_type = :object_type' using l_object_type;
  fetch c1 into l_count;
  DBMS_OUTPUT.put_line('You have ' || l_count || ' views');
  close c1;
  l_object_type := 'INDEX';
  open c1 for 'SELECT count(*) from user_objects where object_type = :object_type' using l_object_type;
  fetch c1 into l_count;
  close c1;
  DBMS_OUTPUT.put_line('You have ' || l_count || ' indexes');
END;
You have 32 tables
You have 0 views
You have 57 indexes
Statement processed.

如果不想声明自己的ref游标类型,可以使用预先构建的SYS_REFCURSOR类型。

最新更新