The RETURN statement terminates the execution of a stored function and returns the result to the caller.
Syntax
RETURN expr
Parameters
Parameter |
Description |
|---|---|
| expr | The expression to return. Its type must be compatible with the return type specified in the RETURNS clause of the function definition. |
A stored function must have at least one RETURN statement. If the function has multiple exit points, it can have multiple RETURN statements.
Stored procedures and triggers do not use the RETURN statement to exit; instead, they use the LEAVE statement.
Examples
Use the RETURN statement 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
Use multiple RETURN statements in a conditional function:
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
