Example: custlist.4gl (Function custarr_fill)
The custarr_fill function fetches rows from the customer SQL table,
according to the SQL condition passed as parameter.
The custarr_fill function in custlist.4gl:
1 PRIVATE FUNCTION custarr_fill(sql_cond STRING) RETURNS INTEGER
2 DEFINE sql_text STRING,
3 rec t_custrec,
4 x INTEGER
5
6 LET sql_text = "SELECT * FROM customer"
7 IF sql_cond IS NOT NULL THEN
8 LET sql_text = sql_text || " WHERE " || sql_cond
9 END IF
10 LET sql_text = sql_text || " ORDER BY cust_name"
11
12 DECLARE ca_curs CURSOR FROM sql_text
13
14 CALL custarr.clear()
15 CALL custatt.clear()
16 FOREACH ca_curs INTO rec.*
17 LET x = x + 1
18 LET custarr[x] = rec
19 IF rec.state == "IL" THEN
20 LET custatt[x].cust_name = "red"
21 END IF
22 END FOREACH
23
24 CLOSE ca_curs
25 FREE ca_curs
26
27 RETURN custarr.getLength()
28
29 END FUNCTION
Note:
- Line
1declares the function, with the SQL condition asSTRINGparameter. The function returns a singleINTEGERvalue, representing the number of rows fetched. - Lines
6thru10build the SQL statement to fetch rows from the customer table. If the SQL condition passed as parameter is notNULL, we add aWHEREclause to theSELECT. - Line
12declares an SQL cursor from theSELECTstatement created in the previous lines. - Line
14clears thecustarrprogram array for the data. - Line
15clears thecustattprogram array for cell decoration attributes. - Line
16thru22implement theFOREACHloop, to fetch rows from the SELECT result set into the program array. - Line
16: TheFOREACHinstruction opens the SQL cursor, and fetchs rows one by oneINTOthe specified record. For each of the fetched rows, the body of theFOREACHloop is executed. - Line
17increments the index variable by one. - Line
18copies the values from the record variable into the array element at index specified by thexvariable. Both record and array elements are defined with the same structure, from thet_custrectype. - Line
19thru21: If the state equals"IL", we set aredcolor for the customer name cell in thecustattdecoraction array. The decoration array will be used by theDISPLAY ARRAYinstruction, with theDIALOG.setArrayAttributes()method. As discussed in Example custlist.4gl (Function custarr_display). - Lines
24and25close the SQL cursor and free resources used by this cursor. Since all the required data is now in memory in the program array, we don't need the SQL cursor anymore. - Line
27returns the number of rows found, by using thegetLength()method of the program array.