Cursor predicates
Cursor predicates are SQL keywords that can be used to determine the state of a cursor defined within the current scope. They provide a means for easily referencing whether a cursor is open, closed or if there are rows associated with the cursor.
Cursor predicates can be referenced in SQL and SQL PL statements
wherever the status of a cursor can be used as a predicate condition.
The cursor predicates that can be used include:
- IS OPEN
- This predicate can be used to determine if the cursor is in an open state. This can be a useful predicate in cases where cursors are passed as parameters to functions and procedures. Before attempting to open the cursor, this predicate can be used to determine if the cursor is already open.
- IS NOT OPEN
- This predicate can be used to determine if the cursor is closed. Its value is the logical inverse of IS OPEN. This predicate can be useful to determine whether a cursor is closed before attempting to actually close the cursor.
- IS FOUND
- This predicate can be used to determine if the cursor contains
rows after the execution of a FETCH statement. If the last FETCH statement
executed was successful, the IS FOUND predicate value is true. If
the last FETCH statement executed resulted in a condition where rows
were not found, the result is false. The result is unknown when:
- the value of cursor-variable-name is null
- the underlying cursor of cursor-variable-name is not open
- the predicate is evaluated before the first FETCH action was performed on the underlying cursor
- the last FETCH action returned an error
An alternative to using IS FOUND is to use IS NOT FOUND which has the opposite value.
Examples
The following script defines an SQL procedure that contains references to these predicates as well as the prerequisite objects required to successfully compile and call the procedure:CREATE TABLE T1 (c1 INT, c2 INT, c3 INT)@
insert into t1 values (1,1,1),(2,2,2),(3,3,3) @
CREATE TYPE myRowType AS ROW(c1 INT, c2 INT, c3 INT)@
CREATE TYPE myCursorType AS myRowType CURSOR@
CREATE PROCEDURE p(OUT count INT)
LANGUAGE SQL
BEGIN
DECLARE C1 cursor;
DECLARE lvarInt INT;
SET count = -1;
SET c1 = CURSOR FOR SELECT c1 FROM t1;
IF (c1 IS NOT OPEN) THEN
OPEN c1;
ELSE
set count = -2;
END IF;
set count = 0;
IF (c1 IS OPEN) THEN
FETCH c1 into lvarInt;
WHILE (c1 IS FOUND) DO
SET count = count + 1;
FETCH c1 INTO lvarInt;
END WHILE;
ELSE
SET count = 0;
END IF;
END@
CALL p()@