Summary of Cursor Positioning¶
The following table summarizes the effects of cursor statements on cursor positioning:
| Statement | Effect on Cursor Position |
|---|---|
| OPEN | Cursor positioned before first row in set. |
| FETCH | Cursor moves to next row in set. If it is already on the last row, the cursor moves beyond the set and its position becomes undefined. |
| CLOSE | Cursor and set of rows become undefined. |
Dynamically Specifying Cursor Names¶
A dynamically specified cursor name (a cursor name specified using a host string variable) can be used to scan a table that contains rows that are related hierarchically, such as a table of employees and managers.
In a relational database, this tree structure is represented as a relationship between two columns. In an employee table, employees are assigned an ID number. One of the columns in the employee table contains the ID number of each employee’s manager. The ID number column establishes the relationships between employees and managers.
To use dynamically specified cursor names to scan this kind of table, do the following:
- Write a routine that uses a cursor to retrieve all the employees that work for a manager.
- Create a loop that calls this routine for each row that is retrieved and dynamically specifies the name of the cursor to be used by the routine.
The following example retrieves rows from the employee table, which has the following format:
This program scans the employee table and prints out all employees and the employees that they manage.
/* This subroutine retrieves and displays employees who report to a given manager. This subroutine is called recursively to determine if a given employee is also a manager and if so, it will display who reports to them.