Cursors
A cursor is a variable that runs through the tuples of some relation.
This relation can be a stored table, or it can be the answer to some query.
By fetching into the cursor each tuple of the relation, we can write a program to read and process the value of each such tuple.
If the relation is stored, we can also update or delete the tuple at the current cursor position.
The example below illustrates a cursor loop.
It uses our example relation T1(e, f) whose tuples are pairs of integers:
SQL> CREATE TABLE T1 (
2 e INTEGER,
3 f INTEGER );
The program will delete every tuple whose first component is less than the second, and insert the reverse tuple into T1.
06 | CURSOR T1Cursor IS SELECT e, f FROM T1 WHERE e < f FOR UPDATE ; |
11 | FETCH T1Cursor INTO a, b; |
13 | EXIT WHEN T1Cursor% NOTFOUND ; |
15 | DELETE FROM T1 WHERE CURRENT OF T1Cursor; |
17 | INSERT INTO T1 VALUES ( b, a ); |
|
A recent immigrant from Poland needed a drivers license, and went to the state licensing bureau.
When it was time for his eye test, the examiner asked him to read a chart of small letters:
W C Z E W T O S I C Z
“Can you see that clearly and read it back to me?”
“Can I read it?” said the immigrant. “That guy is my best friend.”
|