MySQL Functions
Creating a function
In MySQL, Function can also be created. A function always returns a value using the
return statement. The function can be used in SQL queries.
Syntax
1. CREATE FUNCTION function_name [ (parameter datatype [, parameter dataty
pe]) ]
2. RETURNS return_datatype
3. BEGIN
4. Declaration_section
5. Executable_section
6. END;
Parameter:
Function_name: name of the function
Parameter: number of parameter. It can be one or more than one.
return_datatype: return value datatype of the function
Play Videox
declaration_section: all variables are declared.
executable_section: code for the function is written here.
Example 1
Step 1: Create database and table.
Database: employee
Table 1 : designation
Table 2 : staff
Step 2: Create a function
Function query:
1. DELIMITER $$
2. CREATE FUNCTION get_designation_name(d_id INT) RETURNS VARCHAR( 2
0 )
3. BEGIN
4. DECLARE de_name VARCHAR( 20 ) DEFAULT "";
5. SELECT name INTO de_name FROM designation WHERE id = d_id;
6. RETURN de_name;
7. END $$
Step 3: Execute the function
Query :
SELECT id, get_designation1(`d_id`) as DESIGNATION, name FROM 'staff'
Drop a function
In MySQL Function can also be dropped. When A function id dropped, it is removed
from the database.
Syntax:
1. Drop function [ IF EXISTS ] function_name;
Parameter
function_name: name of the function to be dropped.
Example 1:
drop function get_designation_name;
Next Topic MySQL