Detect end of data
In the previous example, the WHILE condition prevents
execution of the loop in case the OPEN statement returns an error.
The same condition terminates the loop when SQLCODE is set to
100
to
signal the end of data. However, the loop contains a test of SQLCODE.
This test is necessary because, if the SELECT statement is valid yet
finds no matching rows, the OPEN statement returns a zero, but the
first fetch returns 100
(end of data) and no data.
The following example shows another way to write the same loop: EXEC SQL DECLARE the_item CURSOR FOR
SELECT order_num, item_num, stock_num
INTO :o_num, :i_num, :s_num
FROM items;
EXEC SQL OPEN the_item;
if(SQLCODE == 0)
EXEC SQL FETCH the_item; /* fetch 1st row*/
while(SQLCODE == 0)
{
printf("%d, %d, %d", o_num, i_num, s_num);
EXEC SQL FETCH the_item;
}
In this version, the case of no returned rows is handled early, so no second test of SQLCODE exists within the loop. These versions have no measurable difference in performance because the time cost of a test of SQLCODE is a tiny fraction of the cost of a fetch.