The RETURN statement terminates the execution of a stored function and returns the result to the function caller.
Syntax
RETURN expr
Parameters
Parameter |
Note |
|---|---|
| expr | The expression to be returned must have a type that matches the type specified in the function definition. RETURNS The return types specified by the clauses are compatible. |
A stored function must have at least one RETURN statement. If the function has multiple exit points, there may be multiple RETURN statements.
In stored procedures and triggers, the RETURN statement is not used; instead, the LEAVE statement is used to exit the program.
Examples
Use RETURN in a stored function to return a result.
obclient> DELIMITER //
obclient> CREATE FUNCTION calculate_double(n INT)
RETURNS INT
DETERMINISTIC
BEGIN
RETURN n * 2;
END //
obclient> DELIMITER ;
obclient> SELECT calculate_double(5);
The query result is as follows:
+-------------------+
| calculate_double(5) |
+-------------------+
| 10 |
+-------------------+
1 row in set
Using multiple RETURN statements in a function with conditional execution:
obclient> DELIMITER //
obclient> CREATE FUNCTION get_status(score INT)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
IF score >= 90 THEN
RETURN 'excellent';
ELSEIF score >= 60 THEN
RETURN 'pass';
ELSE
RETURN 'fail';
END IF;
END //
obclient> DELIMITER ;
obclient> SELECT get_status(85);
The query result is as follows:
+----------------+
| get_status(85) |
+----------------+
| pass |
+----------------+
1 row in set