Creating the Function

The main module, cust_stub.4gl calls the library function display_custarr, which uses a cursor with a FOREACH statement to load rows from the customer table into a program array. The DISPLAY ARRAY statement displays the records in the program array to the screen array defined in the form specification file.

Program Arrays

A program array is an ordered set of elements all of the same data type. You can create one-, two-, or three-dimensional arrays. The elements of the array can be simple types or they can be records.

Arrays can be:

  • static - defined with an explicit size for all dimensions.

  • dynamic - has a variable size. Dynamic arrays have no theoretical size limit.

All elements of static arrays are initialized even if the array is not used. Therefore, defining huge static arrays may use a lot of memory. The elements of dynamic arrays are allocated automatically by the runtime system, as needed.

Example of a dynamic array of records definition:

01 DEFINE cust_arr DYNAMIC ARRAY OF RECORD 
02                    store_num LIKE customer.store_num,
03                    city      LIKE customer.city 
04                 END RECORD

This array variable is named cust_arr; each element of the array contains the members store_num and city. The size of the array will be determined by the runtime system, based on the program logic that is written to fill the array. The first element of any array is indexed with subscript 1. You would access the store_num member of the 10th element of the array by writing cust_arr[10].store_num.

Loading the Array: the FOREACH Statement

The FOREACH statement is equivalent to using the OPEN, FETCH and CLOSE statements to retrieve and process all the rows selected by a query, and is especially useful when loading arrays.

To load the program array in the example, you must retrieve the values from the result set of a query and load them into the elements of the array. You must DECLARE the cursor before the FOREACH statement can retrieve the rows.
01 DECLARE custlist_curs CURSOR FOR 
02        SELECT store_num, city FROM customer 
03  CALL cust_arr.clear()
04  FOREACH custlist_curs INTO cust_rec.*
05      CALL cust_arr.appendElement()
06      LET cust_arr[cust_arr.getLength()].* = cust_rec.*
07  END FOREACH

The FOREACH statement shown:

  1. Opens the custlist_curs cursor.
  2. Clears the cust_arr array.
  3. Fetches a row into the record cust_rec. This record must be defined as having the same structure as a single element of the cust_arr array (store_num, city).
  4. Appends an empty element to the cust_arr array.
  5. Copies the cust_rec record into the array cust_arr using the getLength method to determine the index of the element that was newly appended to the array.
  6. Repeats steps 3, 4 and 5 until no more rows are retrieved from the database table (automatically checks for the NOTFOUND condition).
  7. Closes the cursor and exits from the FOREACH loop.