Monday 8 June 2015

Ref Cursor in PL/SQL

      Ref cursor or Cursor Variable is a pointer to a result set in database. Ref cursor is the pl/sql datatype whose value is the memory address of a query work area in database.

Characteristics of a Ref Cursor:
1) Ref cursor refers to the Memory address on the database.
2) A ref cursor involves an additional database round trip. The data is not to be retrieved until the user attempts to read it.
3) Ref Cursor is not updatable. You cannot update the database by using Ref cursor.
4) A Ref Cursor is not backward scrollable. The data represented by the Ref Cursor is accessed in forward-only serial manner.
5) A Ref-Cursor is PL/SQL datatype. You create and return a ref cursor in PL/SQL Block.

Difference between Normal cursor and Ref Cursor:
1) Cursor doesn't have a return type but A Reference Cursor have a return type
2) REF cursor can be assigned dynamically while Normal cursor once defined cann't be changed.
3) Ref cursor can be associated with many no. of sql statements where cursor can be associated only with one sql statement.
4) Using Ref Cursor we can pass cursor data as parameter to the procedure or function but in normal cursor it is not.

Types of Ref Cursor:

There are 2 types of Ref Cursor

1) Strongly Typed Ref Cursor:
Ref Cursor with Return type is called strongly typed Ref Cursor.

2) Weakly Typed Ref Cursor:
Ref Cursor without return type is called weakly Typed Ref Cursor.

General Syntax:
TYPE cursor_name IS REF CURSOR [RETURN return_type];
Example for Strongly typed Ref Cursor:

Table creation Script


PL/SQL Block for Strongly Typed ref cursor:
 

OUTPUT:







Example for Weakly Typed Ref Cursor:

Refer the same table created above.


Output:









Difference between Strongly Typed and Weakly typed Ref Cursor:
1) A strongly typed cursor always returns a known Type . But weakly typed ref Cursor has return type that depends on the SQL query executed.
2) In Strongly typed Ref Cursor the Compiler find the problems in a PL/SQL Block by comparing the types returned. But In weakly typed Ref cursors compiler cannot find the problem at compile time.
3) In strongly typed Dynamic query is not possible but in weakly typed Dynamic Query is possible.

SYS_REFCURSOR:
SYS_REFCURSOR is same as the weekly typed ref cursor and that can be used to pass cursors from and to a stored procedure.
If you are using SYS_REFCURSOR then no need to use the TYPE for declaration.

General Syntax :
Ref_cursor_name SYS_REFCURSOR;

Create a procedure and use the same table created above.


Call the procedure by passing ref cursor


Output:

No comments: