Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Database Systems

and Web
(15B11CI312)
Database Systems and Web

Lecture: Stored Functions, Cursors


Contents to be covered
▪Error Handling in Stored Procedure
▪Stored Function
▪ Create Stored Function
▪ Drop Function
▪ Stored Procedure vs. Function
▪ Cursors
Error Handling in Stored Procedures

DECLARE action HANDLER FOR condition_value statement;

❑ There are two options as action:


❖ CONTINUE : The execution of the enclosing code block ( BEGIN … END ) continues.
❖ EXIT : The execution of the enclosing code block, where the handler is declared, terminates.
Error Handling in Stored Procedures

DECLARE action HANDLER FOR condition_value


statement;

❑ The condition_value specifies a particular condition or a class of conditions that activate the handler.

❑ The condition_value accepts one of the following values:


❖ A MySQL error code.
❖ A standard SQL STATE value : SQL WARNING, NOT FOUND or SQL EXCEPTION condition.
❖ A named condition associated with either a MySQL error code or SQLSTATE value.
Error Handling in Stored Procedures

DECLARE action HANDLER FOR condition_value


statement;

❑ The statement could be a simple statement or a compound statement enclosing by


the BEGIN and END keyword.
MYSQL Error Handling Example
❑ This handler set the value of the hasError variable to 1 and continue the execution if
an SQLEXCEPTION occurs.

DECLARE CONTINUE HANDLER FOR


SQLEXCEPTION
SET hasError = 1;
❑ This handler rolls back the previous operations, issues an error message, and exit the current code
block in case an error occurs. If you declare it inside the BEGIN END block of a stored procedure, it
will terminate the stored procedure immediately.

DECLARE EXIT HANDLER FOR SQLEXCEPTION


BEGIN
ROLLBACK;
SELECT 'An error has occurred, operation rollbacked and the stored procedure was terminated'; END;
Stored Function
❑ A special kind stored program that returns a single value.

❑ Encapsulate common formulas or business rules that are reusable among SQL statements or
stored programs.

❑To create a stored function CREATE FUNCTION statement is used.


Create Stored Function
DELIMITER $$ ❑ Specify the name of function after CREATE
FUNCTION keyword.
CREATE FUNCTION function_name(
❑ List all parameters inside the parentheses followed by the
param1, param2,… function name. By default, all parameters are
) the IN parameters. You cannot
RETURNS datatype specify IN , OUT or INOUT modifiers to parameters.
[NOT] DETERMINISTIC ❑ Specify the data type of the return value in
BEGIN the RETURNS statement.
- - statements ❑ A deterministic function always returns the same result
for the same input parameters whereas a non-deterministic
END $$ function returns different results for the same input
parameters. MySQL uses the NOT
DELIMITER ; DETERMINISTIC option by default.
❑ Inside the body section, specify at least
one RETURN statement.
Create a function that returns the addition of two numbers
DELIMITER $$
CREATE FUNCTION AddNumbers(
val1 DECIMAL(10,2)
val2 DECIMAL(10,2) )
RETURNS DECIMAL(15,2) mysql> SET @Output = AddNumbers(42);
DETERMINISTIC
mysql> SELECT @Output;
BEGIN
DECLARE Output DECIMAL(15,2) ;

Output = val1 + val2;

- - return the output


RETURN (Output);
END$$

DELIMITER ;
Create a function that returns the customer level based on credit
and call function from stored procedure

1. Create Stored Function

2. Create Procedure and call function


inside it

3. Call Procedure
Create a function that returns the customer level based on credit and
call function from stored procedure
DELIMITER $$
CREATE FUNCTION CustomerLevelData(
credit DECIMAL(10,2) )
RETURNS VARCHAR(20)
DETERMINISTIC 1. Create Function CustomerLevelData()
BEGIN
DECLARE customer_Level VARCHAR(20);

IF credit > 60000 THEN


SET customer_Level = 'PLATINUM';
ELSEIF (credit <= 60000 AND credit >= 20000) THEN
SET customer_Level = 'GOLD';
ELSEIF credit < 20000 THEN
SET customer_Level = 'SILVER';
END IF;

- - return the customer level


RETURN (customer_Level);
END$$

DELIMITER ;
Create a function that returns the customer level based on credit and
call function from stored procedure
DELIMITER $$
CREATE PROCEDURE GetCustomerLevelData(
IN customer_No INT,
OUT customer_Level VARCHAR(20) )
BEGIN 2. Create Procedure GetCustomerLevel()
DECLARE credit DEC(10,2) DEFAULT 0;
3. Call Procedure GetCustomerLevel()
- - get credit limit of a customer
SELECT creditLimit INTO credit FROM customers
WHERE customerNumber = customer_No; CALL GetCustomerLevelData(100, @custLevelIfo);

- - call the function SELECT @custLevelInfo;


SET customer_Level = CustomerLevelData(credit);
END$$
DELIMITER ;
Calling a stored function in an SQL
statement

SELECT
customerName,
CustomerLevelData(creditLimit)
FROM customers
ORDER BY customerName;
Drop Function
DROP FUNCTION [IF EXISTS]
function_name;
❑ While dropping a function that does not exist by using the IF EXISTS option, MySQL issues a
warning .

❑ Otherwise, MySQL issues an error.

To Drop “CustomerLevelData()” function:

DROP FUNCTION [IF EXISTS] CustomerLevelData();


Function
❑ Stored function cannot execute a stored procedure inside a function,
❑ A function is not allowed to modify database state, and stored
procedures are allowed to modify database state.
Stored Procedure vs. Function
❑ The function must return a value, but in Stored procedure it is optional. Even a stored procedure can return
zero or n values.
❑ Functions can be called from Stored procedures while a Stored procedure cannot be called from a function.
❑ The procedure allows to write INSERT, UPDATE, DELETE statements with SELECT statement while
function only allows SELECT statement.
❑ Procedures cannot be utilized in a SELECT statement while a function can be embedded in a SELECT
statement.
❑ Stored procedures cannot be used in SQL statements like WHERE/HAVING/SELECT statement whereas
functions can be used.
❑ We can use transactions in Stored procedures while transactions cannot be used in functions.
MYSQL Cursor
❑ MySQL cursors are used to handle a result set inside a stored procedure.

❑ A cursor is a SELECT statement that is defined within the declaration section of MySQL stored
program.

❑ Cursor iterates a set of rows of result set and process each row individually.

❑ MySQL cursor is read-only, non-scrollable and asensitive:


❖ Read-only: Cannot update data in the underlying table through the cursor.
❖ Non-scrollable: Can not fetch rows in reverse order and can not skip rows or jump to a
specific rows in result set. Only fetch rows in the order determined by the SELECT
statement.
❖ Asensitive: Points to the actual data(Not to temporary copy of data).
Working of MySQL cursor
1. Declare the cursor to initialize in the memory.

2. Open the cursor to allocate memory.

3. Fetch the cursor to retrieve data.

4. Close the cursor to release allocated memory.


Declare MYSQL Cursor
❑ Declaration of MYSQL cursor must be after any variable declaration.

❑ Declaring a cursor before the variable declarations lead to, MySQL error.

❑ A cursor must always associate with a SELECT statement.

DECLARE cursor_name CURSOR FOR


SELECT_statement;
Open MYSQL Cursor
❑ OPEN a cursor initializes the result set.

❑ Call the OPEN statement before fetching rows from the result set.

OPEN cursor_name;
Fetch MYSQL Cursor
❑ FETCH statement retrieve the data from the row pointed by the cursor and then move the cursor
to the next row in the result set.

FETCH cursor_name INTO variables


list;
Close MYSQL Cursor
❑ When there is no row available to fetch data, close cursor to release the memory associated with
it.

CLOSE cursor_name;
Handler in MYSQL Cursor
❑ To handle the situation when the cursor could not find any row, declare a NOT
FOUND handler.
❑ The handler declaration must appear after variable and cursor declaration inside the stored
procedures
❑ finished variable: Indicates that the cursor has reached the end of the result set.

DECLARE CONTINUE HANDLER FOR NOT FOUND SET


finished = 1;
Note: For each FETCH statement, the cursor collect data from next row of the result set. There will be a situation that the
cursor reaches the end of the result set, it will not be able to get the data, and a condition is raised.
Create a stored procedure that generate an email list of all
employees in the employees table
1. Create Procedure

2. Declare some variables, a cursor for looping over the emails of employees, and a NOT
FOUND handler

3. Open the cursor

4. Iterate the email list, and concatenate all emails where each email is separated by a (;)

5. Inside the loop, use the finished variable to check if there is an email in the list to terminate the
loop.

6. Close the cursor.


DELIMITER $$
1
CREATE PROCEDURE createEmailList (
INOUT emailList varchar(4000) ) 2
BEGIN 3
DECLARE finished INTEGER DEFAULT 0;
4
DECLARE emailAddress varchar(100) DEFAULT “ “ ;
-- declare cursor for employee email 5
DECLARE curEmail 6
CURSOR FOR
SELECT email FROM employees;
- - declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished
= 1;
OPEN curEmail; SET @emailList = “ “ ;
getEmail: LOOP CALL createEmailList(@emailList);
FETCH curEmail INTO emailAddress; SELECT @emailList;
IF finished = 1 THEN
LEAVE getEmail;
END IF;
- - build email list
SET emailList = CONCAT(emailAddress,";",emailList); END
LOOP getEmail;
CLOSE curEmail;
END$$
DELIMITER ;
References
1. https://www.mysqltutorial.org/
2. https://www.javatpoint.com/
3. Murach's MySQL, 3rd edition by Joel Murach.

You might also like