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

CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ]   

RETURNS return_datatype  

BEGIN  

Declaration_section  

Executable_section  

END;  

Parameter:

Function_name: name of the function

Parameter: number of parameters. It can be one or more than one.

return_datatype: return value datatype of the function

declaration_section: all variables are declared.

executable_section: code for the function is written here.

DELIMITER $$   

CREATE FUNCTION get_designation_name(d_id INT) RETURNS VARCHAR( 20 )   

BEGIN   

DECLARE de_name VARCHAR( 20 ) DEFAULT “”;  

SELECT name INTO de_name FROM designation WHERE id = d_id;  

RETURN de_name;  

END $$

Drop a function

In MySQL Function can also be dropped. When A function id is dropped, it is removed from the database.

Syntax:

Drop function [ IF EXISTS ] function_name;  

Parameter

function_name: name of the function to be dropped.

drop function get_designation_name;