Cursors (Cont.)


Below are explanations for the previous program:
Line 01: DECLARE
Introduce the declaration section.

Line 02: /* Output variables to hold the result of the query: */
Everything between the two markers “/*” and “*/” is a comment.

Line 03: a T1.e%type;
It declares a variable a to have a type equal to the type of attribute e of the relation T1:
     SQL> CREATE TABLE  T1 (
       2    e  INTEGER,
       3    f  INTEGER );
Although we know these types are INTEGER, we wisely make sure that whatever types they may have are copied to the PL/SQL variables.

Line 04: b T1.f%type;
It declares variable b to have a type equal to the type of attribute f of the relation T1.

Line 06: CURSOR T1Cursor IS SELECT e, f FROM T1 WHERE e < f FOR UPDATE;
Define the cursor T1Cursor. It ranges over a relation defined by the SELECT-FROM-WHERE query. That query selects those tuples of T1 whose first component is less than the second component. It declares the cursor FOR UPDATE since we will modify T1 using this cursor later on Line 15.

Line 07: BEGIN
Begin the executable section of the program.

Line 08: OPEN T1Cursor;
Open the cursor, an essential step.
DECLARE
  /* Output variables to hold the result of the query: */
  a  T1.e%type;
  b  T1.f%type;
  /* Cursor declaration: */
  CURSOR  T1Cursor  IS SELECT  e, f  FROM  T1  WHERE  e < f  FOR UPDATE;
BEGIN
  OPEN  T1Cursor;
  LOOP
    /* Retrieve each row of the result of the above query into PL/SQL variables: */
    FETCH  T1Cursor  INTO  a, b;
    /* If there are no more rows to fetch, exit the loop: */
    EXIT WHEN  T1Cursor%NOTFOUND;
    /* Delete the current tuple: */
    DELETE FROM  T1  WHERE CURRENT OF  T1Cursor;
    /* Insert the reverse tuple: */
    INSERT INTO  T1  VALUES( b, a );
  END LOOP;
  /* Free cursor used by the query. */
  CLOSE  T1Cursor;
END;




      “The Cryptogram” is full of wit, though it’s not exactly a barrel of laughs.