Difference Between Cursor And Ref Cursor

Example of Cursor:

    cursor c1 is select first_name, salary from hr.employees;
    for c in c1 
        dbms_output.put_line('Ename: ' || c.first_name || ', Salary: ' || c.salary);
    end loop;

Example of Ref Cursor

    ename varchar2(10);
    sal number;
    open c1 for select first_name, salary from hr.employees;
        FETCH c1 into ename, sal;
            EXIT WHEN c1%NOTFOUND;
        dbms_output.put_line('Ename: ' || first_name || ', Salary: ' || salary);
    close c1;    

They are both cursors and can be processed in the same fashion and at the most basic level, they both are same. There are some important differences between regular cursors and ref cursors which are following:

  1. A ref cursor can not be used in CURSOR FOR LOOP, it must be used in simple CURSOR LOOP statement as in example.

  2. A ref cursor is defined at runtime and can be opened dynamically but a regular cursor is static and defined at compile time.

  3. A ref cursor can be passed to another PL/SQL routine (function or procedure) or returned to a client. A regular cursor cannot be returned to a client application and must be consumed within same routine.

  4. A ref cursor incurs a parsing penalty because it cannot cached but regular cursor will be cached by PL/SQL which can lead to a significant reduction in CPU utilization.

  5. A regular cursor can be defined outside of a procedure or a function as a global package variable. A ref cursor cannot be; it must be local in scope to a block of PL/SQL code.

  6. A regular cursor can more efficiently retrieve data than ref cursor. A regular cursor can implicitly fetch 100 rows at a time if used with CURSOR FOR LOOP. A ref cursor must use explicit array fetching.

Use of ref cursors should be limited to only when you have a requirement of returning result sets to clients and when there is NO other efficient/effective means of achieving the goal.


Ask Tom

Read More