A function is a special type of stored program that can return a value and has only IN parameters.
Function structure
The structure of a function is as follows. Compared with stored procedures, a function must contain at least one or more RETURNS clauses:
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...]
BEGIN -- Start execution
SQL statement; [ SQL statement; ...]
END; -- End execution
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic: {
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
}
Creating functions
You can create a function by using the CREATE FUNCTION statement. The following conditions must be met:
The function must have a return value.
All functions must have at least one
RETURNSstatement.A function must be used in an expression with other statements.
If an exception occurs during the evaluation of the expression in a
RETURNstatement and is caught by theHANDLERinside the function, the function returnsNULLinstead of raising theFUNCTION ended without RETURNerror. This behavior takes effect starting from V4.4.2 BP4, and some V4.4.2.2 patch versions have already included this fix.
Here is an example:
obclient> CREATE FUNCTION my_func (c1 CHAR(20)) RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Thank ',c1,'!');
Query OK, 0 rows affected
obclient> SELECT my_func('You');
+----------------+
| my_func('You') |
+----------------+
| Thank You! |
+----------------+
1 row in set