Example: custdata.4gl (Function cust_orders_count)

The cust_orders_count function returns the number of orders referencing the customer number passed as parameter.

The cust_orders_count function in custdata.4gl:
  1 PUBLIC FUNCTION cust_orders_count(curr_cust t_cust_num) RETURNS INTEGER
  2   DEFINE cnt INTEGER
  3   SELECT COUNT(*) INTO cnt FROM orders WHERE cust_num = curr_cust
  4   RETURN cnt
  5 END FUNCTION
Note:
  • Line 1 defines the function, with a curr_cust parameter defined with the t_cust_num type (go to Example: custdata.4gl (top definitions) for more details)
  • Line 2 defines a local function variable that will hold the number of order rows found.
  • Line 3 executes the SELECT statement to find the number of order rows referencing the customer number passed as parameter.
  • Line 4 returns the number of order rows found.

Note that this code does not check for SQL errors with a TRY/CATCH block: SQL statements such as this SELECT should never fail. If it fails, in means that the SQL table does not exist or one of the column names is wrong. In both cases it's a fatal error that should stop program execution.