Example: custquery.4gl (Function get_cust_cnt)
This function is called by the function query_cust to return the count
of rows that would be retrieved by the SELECT statement. The criteria previously
entered by the user and stored in the variable where_clause is used.
Function
get_cust_cnt: 1 FUNCTION get_cust_cnt(p_where_clause STRING) RETURNS INTEGER
2 DEFINE sql_text STRING,
3 cust_cnt INTEGER
4 LET sql_text = "SELECT COUNT(*) FROM customer WHERE " || p_where_clause
5 PREPARE cust_cnt_stmt FROM sql_text
6 EXECUTE cust_cnt_stmt INTO cust_cnt
7 FREE cust_cnt_stmt
8 RETURN cust_cnt
9 END FUNCTIONNote:
- Line
1: The function accepts as a parameter the value ofwhere_clause, and returns a singleINTEGERvalue. - Line
2defines a function variable,sql_text, to hold the complete text of the SQLSELECTstatement. - Line
3defines a function variablecust_cntto hold the count returned by theSELECTstatement. - Lines
4builds the string containing the complete SQLSELECTstatement, concatenatingp_where_clauseat the end using the || operator. Notice that the wordWHEREmust be provided in the string. - Line
5uses thePREPAREinstruction to convert the string into an executable SQL statement, parsing the statement and storing it in memory. The prepared statement is modular in scope. The prepared statement has the identifiercust_cnt_stmt. - Line
6executes the SQLSELECTstatement contained incust_cnt_stmt, using theEXECUTE ... INTOsyntax to store the value returned by the statement in the variablecust_cnt. This syntax can be used if the SQL statement returns a single row of values. - Line
7: TheFREEstatement releases the memory associated with the prepared statement, since this statement is no longer needed. - Line
8returns the value ofcust_cntto the calling function.