Lecture 05.5 SQL StoredFunctions 7
Lecture 05.5 SQL StoredFunctions 7
Stored Functions
1/7
Stored Functions
Refer Joel Murach, Murach’s MySQL, 2nd Edition, 2015, ISBN-13: 978-1890774820
Murach's MySQL, C15 © 2015, MIKE MURACH & ASSOCIATES, INC. 2/7
Stored Functions
• Create your own functions, called as stored functions, user-defined functions (UDFs), or just functions
• With MySQL, a function can only return a single value
• This type of function is called a scalar function
•In many ways, the code for creating a function works similarly to the code for creating a stored procedure
• However, there are two primary differences between stored procedures and functions.
• First, a MySQL function always returns a single value
• Second, a function can’t make changes to the database such as executing an INSERT, UPDATE, or DELETE statement
3/7
Differences between Stored procedure and function
Functions Procedures
A function has a return type and returns a A procedure does not have a return type. But it
value. returns values using the OUT parameters.
You cannot use a function with Data You can use DML queries such as insert, update,
Manipulation queries. Only Select queries are select etc… with procedures.
allowed in functions.
A function does not allow output parameters A procedure allows both input and output
parameters.
You cannot manage transactions inside a You can manage transactions inside a procedure.
function.
You cannot call stored procedures from a You can call a function from a stored procedure.
function
You can call a function using a select statement. You cannot call a procedure using select
statements.
4/7
Example: Stored Function to Retrieve
Value
--A function that returns the vendor ID that matches a vendor’s name DELIMITER //
DELIMITER //
CREATE FUNCTION get_vendor_id
(
vendor_name_param VARCHAR(50)
)
RETURNS INT
BEGIN
◦ DECLARE vendor_id_var INT;
◦ SELECT vendor_id INTO vendor_id_var FROM vendors
◦ WHERE vendor_name = vendor_name_param;
◦ RETURN(vendor_id_var);
END//
--A SELECT statement that uses the function
SELECT invoice_number, invoice_total FROM invoices
WHERE vendor_id = get_vendor_id('IBM')
5/7
Example: Stored Function to Calculate
Value
A function that calculates balance due A statement that calls the function
DELIMITER //
SELECT vendor_id, invoice_number,
get_balance_due(invoice_id) AS balance_due
CREATE FUNCTION get_balance_due FROM invoices
( WHERE vendor_id = 37
invoice_id_param INT
) The response from the system
RETURNS DECIMAL(9,2)
BEGIN
DECLARE balance_due_var DECIMAL(9,2);
RETURN balance_due_var;
END//
6/7
How to Drop a Stored Function
The syntax of the DROP FUNCTION statement The response from the system
DROP FUNCTION [IF EXISTS] function_name
7/7