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 FUNCTION
Note:
- Line
1
: The function accepts as a parameter the value ofwhere_clause
, and returns a singleINTEGER
value. - Line
2
defines a function variable,sql_text
, to hold the complete text of the SQLSELECT
statement. - Line
3
defines a function variablecust_cnt
to hold the count returned by theSELECT
statement. - Lines
4
builds the string containing the complete SQLSELECT
statement, concatenatingp_where_clause
at the end using the || operator. Notice that the wordWHERE
must be provided in the string. - Line
5
uses thePREPARE
instruction 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
6
executes the SQLSELECT
statement contained incust_cnt_stmt
, using theEXECUTE ... INTO
syntax 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
: TheFREE
statement releases the memory associated with the prepared statement, since this statement is no longer needed. - Line
8
returns the value ofcust_cnt
to the calling function.