What is a PL/SQL cursor? Explain with an example.
What is a PL/SQL cursor? Explain with an example.
565
04-Apr-2023
Updated on 04-Apr-2023
Krishnapriya Rajeev
04-Apr-2023A PL/SQL cursor is a mechanism that allows us to retrieve data from a result set one row at a time. It enables us to manipulate data retrieved from a SELECT statement, and it is particularly useful when we need to perform operations on a set of records one at a time.
When processing an SQL statement, a memory area called the context area is created, which contains the information required for processing the statement, such as the number of rows processed. The context area is accessed through a cursor, which is a pointer to the context area that is controlled by PL/SQL. The cursor contains the rows, also referred to as the active set, returned by the SQL statement.
Cursors are of 2 types:
The syntax to create an explicit cursor is as follows:
The steps required to use an explicit cursor are as follows:
Here is an example of how to use a PL/SQL cursor:
In this example, we declare a cursor called "staff_cur" that retrieves the staffno, first name, last name, and salary from the staff table. We then open the cursor and use a loop to retrieve each row of data one at a time using the FETCH statement. We store the retrieved data in variables "staffno", "fname", “lname” and "salary". We increment the count by 1 if the salary is less than 18000. The loop continues until there are no more rows to fetch, which is determined by the NOTFOUND attribute of the cursor. Finally, we close the cursor using the CLOSE statement. The count is then displayed.
Using a cursor in this way allows us to retrieve and manipulate data one row at a time, making it a powerful tool for data processing and analysis.