Cursor in Embedded SQL
A cursor in embedded SQL is a pointer that allows you to retrieve and process one row at a time from the result of a query.
It is mainly used in procedural languages like C, Java, or PL/SQL when a query returns multiple rows, and you need to process them row by row.
Why Use Cursors?
- SQL is set-oriented (returns multiple rows).
- Programming languages are record-oriented (handle one row at a time).
- Cursor helps bridge the gap between SQL and host languages.
Cursor Properties
| Property | Description |
|---|---|
| Name | Identifier used to refer to the cursor |
| Query | The SQL SELECT statement associated with the cursor |
| Position | Points to the current row in the result set |
| State | Can be OPEN, CLOSED, or FETCHED |
| Direction | Can move forward (default), sometimes backward (if supported) |
Steps to Use a Cursor in Embedded SQL
- Declare the Cursor
- Open the Cursor
- Fetch from the Cursor
- Close the Cursor
Example (in Embedded SQL style pseudocode)
Suppose you want to print the names of all employees older than 30.
-- 1. Declare the Cursor
EXEC SQL DECLARE emp_cursor CURSOR FOR
SELECT name FROM Employee WHERE age > 30;
-- 2. Open the Cursor
EXEC SQL OPEN emp_cursor;
-- 3. Fetch rows in a loop
LOOP
EXEC SQL FETCH emp_cursor INTO :emp_name;
IF SQLCODE = 100 THEN -- No more rows
EXIT LOOP;
END IF;
PRINT emp_name;
END LOOP;
-- 4. Close the Cursor
EXEC SQL CLOSE emp_cursor;
Here:
emp_cursoris the cursor name.:emp_nameis a host variable (from the programming language).SQLCODE = 100indicates end of result set.
Summary
| Step | Purpose |
|---|---|
| Declare | Define the cursor with a SELECT query |
| Open | Executes the query |
| Fetch | Retrieves one row at a time |
| Close | Releases resources |
