This tutorial explains how to create and drop functions in MySQL with syntax and examples.
In MySQL, a function is a stored program that you can pass parameters into and then return a value.
Just as you can create functions in other languages, you can create your own functions in MySQL. Let's take a closer look.
The syntax to create a function in MySQL is:
CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ]
RETURNS return_datatype
BEGIN
declaration_section
executable_section
END;
The name to assign to this function in MySQL.
One or more parameters passed into the function. When creating a function, all parameters are considered to be IN parameters (not OUT or INOUT parameters) where the parameters can be referenced by the function but can not be overwritten by the function.
The data type of the function's return value.
The place in the function where you declare local variables.
The place in the function where you enter the code for the function.
Let's look at an example that shows how to create a function in MySQL:
DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
BEGIN
DECLARE income INT;
SET income = 0;
label1: WHILE income = 3000 DO
SET income = income + starting_value;
END WHILE label1;
RETURN income;
END; //
DELIMITER ;
You could then reference your new function as follows:
SELECT CalcIncome (1000);
Once you have created your function in MySQL, you might find that you need to remove it from the database.
The syntax to a drop a function in MySQL is:
DROP FUNCTION [ IF EXISTS ] <strong>function_name</strong>;
The name of the function that you wish to drop.
Let's look at an example of how to drop a function in MySQL.
For example:
DROP FUNCTION CalcIncome;
This example would drop the function called CalcIncome.