A varying-list SELECT statement is one that retrieves data items of varying number and format. Because the number and type of data items are not known, you cannot define host variables in advance.
However, by including the SQLDA in your program, you can use PREPARE to define a SELECT statement and follow it with a DESCRIBE statement. This process inserts the data item information into the SQLDA, which your program can use to execute a SELECT statement. Likewise, record fetches are performed using the SQLDA.
To issue a varying-list SELECT statement:
The following program excerpt shows how to execute a varying-list SELECT statement dynamically.
* include SQLDA copybook.
EXEC SQL
INCLUDE SQLDA
END-EXEC
* assign value to variable sqlcmd.
MOVE 'select * from employee where dept="1050"'
TO sqlcmd
* prepare SELECT command.
EXEC SQL
PREPARE q1 FROM :sqlcmd
END-EXEC
* allocate space for an SQLDA ...
MOVE 20 TO SQLN
* describe SELECT command.
EXEC SQL
DESCRIBE q1 INTO SQLDA
END-EXEC
* make sure SQLDA is big enough.
IF (SQLN <= SQLD)
PERFORM ...
...
MOVE SQLD TO SQLN.
EXEC SQL
DESCRIBE q1 INTO SQLDA
END-EXEC
END-PERFORM
END-IF
* analyze results of DESCRIBE.
...
* allocate storage to hold one row of the result. ...
* declare cursor for SELECT command.
EXEC SQL
DECLARE c1 CURSOR FOR q1
END-EXEC
* open cursor.
EXEC SQL
OPEN c1
END-EXEC
* fetch data into program variables EMPNO, LASTNME and
* FIRSTNME.
EXEC SQL
FETCH c1 USING DESCRIPTOR SQLDA
END-EXEC
* display results fetching next record as long as there
* is one.
PERFORM UNTIL SQLCODE <> 0
DISPLAY ...
EXEC SQL
FETCH c1 USING DESCRIPTOR SQLDA
END-EXEC
END-PERFORM
DISPLAY 'END OF LIST'.
* close cursor.
EXEC SQL
CLOSE c1
END-EXEC