• A cursorin SQL is a database object used to retrieve, process, and
manipulate data one row at a time. While SQL is designed to handle
large data sets in bulk (set-based processing), sometimes we just need
to focus on one row at a time. A cursor in SQL is a temporary
memory or workspace allocated by the database server to process
DML (Data Manipulation Language) operations.
3.
Cursors should beused carefully as they are helpful in scenarios like:
• Performing conditional logic row-by-row.
• Looping through data to calculate or transform fields
• Iterating over result sets for conditional updates or transformations.
• Handling hierarchical or recursive data structures.
• Performing clean-up tasks that can not be done with a single SQL
Query.
4.
Implicit Cursors
• InPL/SQL, when we perform INSERT, UPDATE or DELETE operations,
an implicit cursor is automatically created. This cursor holds the data
to be inserted or identifies the rows to be updated or deleted. We can
refer to this cursor as the SQL cursor in our code.
• Usage: Managed entirely by the SQL engine without explicit
declaration.
5.
Useful Attributes:
• %FOUND:True if the SQL operation affects at least one row.
• %NOTFOUND: True if no rows are affected.
• %ROWCOUNT: Returns the number of rows affected.
• %ISOPEN: Checks if the cursor is open.
6.
• Example: UsingImplicit Cursor for Bulk Updates
This program updates a table by increasing the salary of each
employee by 1500. After the update, the SQL%ROWCOUNT attribute
is used to find out how many rows were affected by the operation.
Query:
DECLARE
total_rows number;
BEGIN
UPDATE Emp
SET Salary = Salary + 1500;
total_rows := SQL%ROWCOUNT;
dbms_output.put_line(total_rows || ' rows updated.');
END;
7.
Explicit Cursors
• Theseare user-defined cursors created explicitly by users for custom
operations. They provide complete control over every part of their
lifecycle: declaration, opening, fetching, closing, and deallocating.
• Usage: Used for fetching data row-by-row with complete control over
the cursor lifecycle.
8.
Explicit cursors areuseful when:
• We need to loop through results manually
• Each row needs to be handled with custom logic
• We need access to row attributes during processing