In this blog post, we will be learning about Oracle PLSQL Cursors.
Following are the topics, we will go through -
1. Cursor - What is a Cursor
2. Different types of Cursor
3. Cursor Attributes
4. Implementation of Cursor - Example
5. For Cursor Loop
6. Parameterized Cursor - Example.
Lets start -
Meaning of Cursor - Acts like a pointer to a context area. When Oracle starts executing any SQL Statement, it allocates an area globally in the server i.e in PGA ( Program Global Area ). This area is the Context area. Cursor acts as a handler to this area.
Types of Cursor - There are two types of Cursor
1. Implicit Cursor
2. Explicit Cursor
Implicit Cursor - As the name suggests, Implicit cursor is managed by Oracle Database, and these type of Cursors don't need to be open or close manually. Oracle does this for programmer.
Implicit Cursor has following attributes -
1. SQL%ROWCOUNT - Returns Number of Rows affected by any 'Select Into', or 'Insert', 'Delete' or 'Update' statement.
2. SQL%FOUND - Returns 'TRUE' ( Boolean ), when one or more rows is affected by any 'Select Into', or 'Insert', 'Delete' or 'Update' statement. Otherwise, it will return FALSE.
3. SQL%NOTFOUND - Returns 'TRUE' ( Boolean ), No row is affected by any 'Select Into', or 'Insert', 'Delete' or 'Update' statement. Otherwise it will return FALSE.
4. SQL%ISOPEN - Checks if the Cursor is still open or has been closed. It would return FALSE, as Implicit Cursor is managed by Oracle and will always Close it after the operation.
5.SQL%BULK_ROWCOUNT - It is a composite attribute and suitable for FORALL Statement. It will return ZERO if, no row is affected by FORALL.
6. SQL%BULK_EXCEPTIONS - Acts like an Associative Array and good to use with FORALL Statement, and it keep tracks of any exception occurred in FORALL.
Explicit Cursor - A cursor that needs to be defined, open and close at the end by the programmer.
Lets see some example -
Here, the explicit cursor 'test_cur' is defined in the 'declaration section', opened and closed in the block.
I used one extra line in below example, to show implicit Cursor - as number of rows affected - test_cur%rowcount.
Cursor for loop - We will see the same example, using cursor for loop and also, we will see its advantages. Here, we have explicitly defined the Cursor.
Same example which sometimes come very handy, is as follows - see the changes in the line, here, we have not defined the Cursor explicitly -
Parameterized Cursor -
Cursor can also be defined based on the parameter passed. Lets see the example, its very clear to understand
Thank you !!