Summary:
See also: Variables, Data Types, Flow Control
The FUNCTION statement defines a named program block containing a set of statements to be executed when the function is invoked.
FUNCTION function-name ( [ argument [,...]
] )
[ define-statement | constant-statement ]
{ fgl-statement | sql-statement | return-statement
} [...]
END FUNCTION
where return-statement is:
RETURN expression [,...]
The data type of each formal argument of the function must be specified by a DEFINE statement that immediately follows the argument list. The actual argument in a call to the function need not be of the declared data type of the formal argument. If data type conversion is not possible, a runtime error occurs.
Function arguments are passed by value (i.e. value is copied on the stack) for basic data types and records, while dynamic arrays and objects are passed by reference (i.e. a handle to the original data is copied on the stack and thus allows modification of the original data inside the function).
Local variables are not visible in other program blocks. The identifiers of local variables must be unique among the variables that are declared in the same FUNCTION definition. Any global or module variable that has the same identifier as a local variable, however, is not visible within the scope of the local variable.
A function that returns one or more values to the calling routine must include the return-statement. Values specified in RETURN must correspond in number and position, and must be of the same or of compatible data types, to the variables in the RETURNING clause of the CALL statement. If the function returns a single value, it can be invoked as an operand within a expression. Otherwise, you must invoke it with the CALL statement with a RETURNING clause. An error results if the list of returned values in the RETURN statement conflicts in number or in data type with the RETURNING clause of the CALL statement that invokes the function.
Any GOTO or WHENEVER ERROR GOTO statement in a function must reference a statement label within the same FUNCTION block.A function can invoke itself recursively with a CALL statement.
01
FUNCTION findCustomerNumber(name)02
DEFINE name CHAR(50)03
DEFINE num INTEGER04
CONSTANT sqltxt = "SELECT cust_num FROM customer WHERE cust_name = ?"05
PREPARE stmt FROM sqltxt06
EXECUTE stmt INTO num USING name07
IF SQLCA.SQLCODE = 100 THEN08
LET num =-109
END IF10
RETURN num11
END FUNCTION