MySQL Stored Procedures and functions
MySQL Stored Procedures and functions
1
Outline
MySQL functions
Built-in functions example
Syntax of a function in MySQL
MySQL Problem and solve with functions
Solution
2
MySQL Functions
Function is a stored program that you can pass parameters into and
then return a value.
Function has a return type and returns a value always.
Function is not allowed with data manipulation queries, select queries
is the only one available.
To call a function you need to use select statement.
We have to two types of functions built-in and user defined functions.
3
Built-In Functions
In order to show all functions in the database use the following syntax
Show function status where Db = ‘name of the Database’;
5
Syntax of a function in MySQL
Remarks:
A deterministic function always returns the same result for the same input
parameters whereas a non-deterministic function returns different results
for the same input parameters.
If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the
NOT DETERMINISTIC option by default.
Datatype: VARCHAR, DECIMAL, INT…….
6
MySQL Problem and solve with
function
Suppose that we have table Customers, how we can see customer
level for each customer from his credit, where customer level is
defined dependent on the range (>100000) PLATINUM, (>=50000,
<=100000) GOLD, (<50000) SILVER
7
Solution
USE `functions`;
DROP function IF EXISTS `CustomerLevel`;
DELIMITER $$
USE `functions`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `CustomerLevel`(credit DECIMAL(10,2) )
RETURNS varchar(20) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE customerLevel VARCHAR(20);
IF (credit > 100000) THEN SET customerLevel = 'PLATINUM';
ELSEIF (credit >= 50000 AND credit <= 100000) THEN SET customerLevel = 'GOLD';
ELSEIF (credit < 50000) THEN SET customerLevel = 'SILVER';
END IF;
RETURN (customerLevel);
END$$
8
DELIMITER ;
Solution(contd.)
9
Example 2
In Sailors Boats Reserve database we want to add the following
feature
When we select the rating we need to add
Excellent if the rating is greater than 9
Above standard if the rating is greater than 7
Standard if the rating is greater than 5
Below standard if the rating is less than 5
10
DROP function IF EXISTS RatingLevel;
DELIMITER $$
CREATE FUNCTION RatingLevel(rate smallint(3)) RETURNS varchar(20) CHARSET
latin1
DETERMINISTIC
BEGIN
DECLARE R_Level VARCHAR(20);
IF (rate>= 9 AND rate<=10) THEN SET R_Level = 'Excellent';
ELSEIF (rate>=7) THEN SET R_Level = 'Above standard';
ELSEIF (rate>= 5) THEN SET R_Level = 'standard';
ELSEIF (rate< 5) THEN SET R_Level = 'Below standard';
END IF;
RETURN (R_Level);
END $$
DELIMITER ;
11
Example 3
In Sailors Boats Reserve database we want to build a function that
computes the number of reserved boats of a sailor
14
Stored Procedures VS Functions
You can use DML queries such as You cannot use a function with
insert, update, select etc… with Data Manipulation queries. Only
procedures. Select queries are allowed in
functions.
A procedure does not have a return A function has a return type and
type. But it returns values using the returns a value.
OUT parameters.
You can call a function from a You cannot call stored procedures
stored procedure. from a function
You cannot call a procedure using You can call a function using a
select statements. select statement.
We can use Transactions in we can't use Transactions in 15
Procedure Function
Stored Procedure Definition
General definition:
DELIMITER //
CREATE PROCEDURE NAME
BEGIN
SQL STATEMENT
END //
DELIMITER ;
Ex:
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
16
Parameters Stored Procedures
Run:
Call GetOfficeByCountry('USA')
17
Parameters Stored
Procedures(contd.)
OUT: the value of an OUT parameter can be changed inside the stored
procedure and its new value is passed back to the calling program
DELIMITER //
CREATE PROCEDURE CountOrderByStatus( IN orderStatus VARCHAR(25), OUT
total INT)
BEGIN
SELECT count(orderNumber) INTO total FROM orders WHERE status =
orderStatus;
END//
DELIMITER ;
Run:
CALL CountOrderByStatus('Shipped',@total);
SELECT @total;
18
Parameters Stored
Procedures(contd.)
DROP PROCEDURE IF EXISTS CountSailorsByRating;
DELIMITER $$
CREATE PROCEDURE CountSailorsByRating ( IN p_rating smallint(3), OUT total
INT)
BEGIN
SELECT count(*) INTO total FROM sailors WHERE rating = p_rating;
END $$
DELIMITER ;
Run:
CALL CountSailorsByRating (7,@total);
SELECT @total;
19
Stored Procedures Problem
20
Stored Procedures Solution
DELIMITER $$
DROP PROCEDURE IF EXISTS update_salary;
CREATE PROCEDURE update_salary ()
BEGIN
DECLARE rowCount INT;
DECLARE currentRow INT;
DECLARE newsalary INT;
SET rowCount=(SELECT COUNT(*) FROM employee);
SET currentRow = 1;
WHILE (currentRow <= rowCount) DO
SET newsalary = (SELECT Salary FROM Employee WHERE id =
currentRow)*(select ExchangeRate from currency WHERE Id= (SELECT
currencyID from employee where id = currentRow));
UPDATE employee SET salaryLBP = newsalary WHERE Id = currentRow;
SET currentRow = currentRow + 1;
END WHILE;
END$$
DELIMITER ; 21