Professional Documents
Culture Documents
L 24 Stored Functions and Cursors
L 24 Stored Functions and Cursors
and Web
(15B11CI312)
Database Systems and Web
❑ The condition_value specifies a particular condition or a class of conditions that activate the handler.
❑ Encapsulate common formulas or business rules that are reusable among SQL statements or
stored programs.
DELIMITER ;
Create a function that returns the customer level based on credit
and call function from stored procedure
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);
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);
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 .
❑ 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.
❑ Declaring a cursor before the variable declarations lead to, MySQL error.
❑ 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.
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.
2. Declare some variables, a cursor for looping over the emails of employees, and a NOT
FOUND handler
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.