0% found this document useful (0 votes)
20 views31 pages

Stored Procedure 1

The document discusses MySQL stored procedures. Some key points: - A stored procedure is a segment of SQL code stored in a database that can be called by applications to perform tasks like running queries or logic. Stored procedures offer advantages like reducing network traffic and centralizing business logic. - MySQL stored procedures allow parameters, which make them more reusable. Parameters can have modes like IN, OUT, and INOUT to determine if values are passed into or out of the procedure. - Variables can be declared and used within stored procedures to store intermediate results. Procedures are created using the CREATE PROCEDURE statement and called using CALL.

Uploaded by

arwinramirez30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
20 views31 pages

Stored Procedure 1

The document discusses MySQL stored procedures. Some key points: - A stored procedure is a segment of SQL code stored in a database that can be called by applications to perform tasks like running queries or logic. Stored procedures offer advantages like reducing network traffic and centralizing business logic. - MySQL stored procedures allow parameters, which make them more reusable. Parameters can have modes like IN, OUT, and INOUT to determine if values are passed into or out of the procedure. - Variables can be declared and used within stored procedures to store intermediate results. Procedures are created using the CREATE PROCEDURE statement and called using CALL.

Uploaded by

arwinramirez30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

MYSQL Stored Procedure

What is Stored Procedure in MSQL?


A stored procedure is a segment of declarative SQL statement stored inside the database
applications such as Java, Python, PHP.
Logic, functional and domain-specific languages => declarative paradigm.
A stored procedure that calls itself is known as a recursive stored procedure. Most database
management system support recursive stored procedures. However, MSQL does not support it
very well.

MySQL stored procedures advantages

1. Reduce network traffic. Stored procedures help reduce the network traffic between
applications and MySQL Server. Because instead of sending multiple lengthy SQL
statements, applications have to send only the name and parameters of stored
procedures.

2. Centralize business logic in the database. You can use the stored procedures to
implement business logic that is reusable by multiple applications. The stored
procedures help reduce the efforts of duplicating the same logic in many applications
and make your database more consistent.

3. Make database more secure. The database administrator can grant appropriate
privileges to applications that only access specific stored procedures without giving any
privileges on the underlying tables.

MySQL stored procedures disadvantages

1. Resource usages. If you use many stored procedures, the memory usage of every
connection will increase substantially. Besides, overusing a large number of logical
operations in the stored procedures will increase the CPU usage because the MySQL is
not well-designed for logical operations.
2. Troubleshooting. It’s difficult to debug stored procedures. Unfortunately, MySQL does
not provide any facilities to debug stored procedures like other enterprise database
products such as Oracle and SQL Server.

3. Maintenances. Developing and maintaining stored procedures often requires a


specialized skill set that not all application developers possess. This may lead to
problems in both application development and maintenance.

MySQL CREATE PROCEDURE statement

This query returns all products in the products table from the sample database.

SELECT * FROM products;

The following statement creates a new stored procedure that wraps the query:

DELIMITER //

CREATE PROCEDURE GetAllProducts()


BEGIN
SELECT * FROM products;
END //

DELIMITER ;

Let’s examine the syntax of the stored procedure

The first and last DELIMITER commands are not a part of the stored procedure. The
first DELIMITER command changes the default delimiter to // and the last DELIMITER command
changes the delimiter back to the default one which is semicolon (;).

To create a new stored procedure, you use the CREATE PROCEDURE statement.

Here is the basic syntax of the CREATE PROCEDURE statement:

CREATE PROCEDURE procedure_name(parameter_list)


BEGIN
statements;
END //
In this syntax

• First, specify the name of the stored procedure that you want to create after
the CREATE PROCEDURE keywords.
• Second, specify a list of comma-separated parameters for the stored procedure in
parentheses after the procedure name. Note that you’ll learn how to create stored
procedures with parameters in the upcoming tutorials.
• Third, write the code between the BEGIN END block. The above example just has a
simple SELECT statement. After the END keyword, you place the delimiter character to
end the procedure statement.

Executing a stored procedure

To execute a stored procedure, you use the CALL statement:

CALL stored_procedure_name(argument_list);

In this syntax, you specify the name of the stored procedure after the CALL keyword. If the
stored procedure has parameters, you need to pass arguments inside parentheses following
the stored procedure name.

This example illustrates how to call the GetAllProducts() stored procedure:

CALL GetAllProducts();

Executing this statement is the same as executing an SQL statement:


Here’s the partial output:

Introduction to MySQL stored procedure parameters

Often, stored procedures have parameters. The parameters make the stored procedure more
useful and reusable. A parameter in a stored procedure has one of three
modes: IN,OUT, or INOUT.

IN parameters

IN is the default mode. When you define an IN parameter in a stored procedure, the calling
program has to pass an argument to the stored procedure.

In addition, the value of an IN parameter is protected. It means that even you change the value
of the IN parameter inside the stored procedure, its original value is unchanged after the stored
procedure ends. In other words, the stored procedure only works on the copy of
the IN parameter.

OUT parameters

The value of an OUT parameter can be changed inside the stored procedure and its new value is
passed back to the calling program.

Notice that the stored procedure cannot access the initial value of the OUT parameter when it
starts.

INOUT parameters

An INOUT parameter is a combination of IN and OUT parameters. It means that the calling
program may pass the argument, and the stored procedure can modify the INOUT parameter,
and pass the new value back to the calling program.
Defining a parameter

Here is the basic syntax of defining a parameter in stored procedures:

[IN | OUT | INOUT] parameter_name datatype[(length)]

In this syntax,

• First, specify the parameter mode, which can be IN , OUT or INOUT depending on the
purpose of the parameter in the stored procedure.
• Second, specify the name of the parameter. The parameter name must follow the
naming rules of the column name in MySQL.
• Third, specify the data type and maximum length of the parameter.

MySQL stored procedure parameter examples

Let’s take some examples of using stored procedure parameters.

The IN parameter example

The following example creates a stored procedure that finds all offices that locate in a country
specified by the input parameter countryName:

DELIMITER //

CREATE PROCEDURE GetOfficeByCountry(


IN countryName VARCHAR(255)
)
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

DELIMITER ;

In this example, the countryName is the IN parameter of the stored procedure.

Suppose that you want to find offices locating in the USA, you need to pass an argument (USA)
to the stored procedure as shown in the following query:

CALL GetOfficeByCountry('USA');
To find offices in France, you pass the literal string France to the GetOfficeByCountry stored
procedure as follows:

CALL GetOfficeByCountry('France')

Because the countryName is the IN parameter, you must pass an argument. If you don’t do so,
you’ll get an error:

CALL GetOfficeByCountry();

Here’s the error:

Error Code: 1318. Incorrect number of arguments for PROCEDURE


classicmodels.GetOfficeByCountry; expected 1, got 0

The OUT parameter example

The following stored procedure returns the number of orders by order status.

DELIMITER $$

CREATE PROCEDURE GetOrderCountByStatus (


IN orderStatus VARCHAR(25),
OUT total INT
)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$

DELIMITER ;

The stored procedure GetOrderCountByStatus() has two parameters:

• The orderStatus: is the IN parameter specifies the status of orders to return.


• The total: is the OUT parameter that stores the number of orders in a specific status.
To find the number of orders that already shipped, you call GetOrderCountByStatus and pass
the order status as of Shipped, and also pass a session variable ( @total ) to receive the return
value.

CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;

To get the number of orders that are in-process, you call the stored
procedure GetOrderCountByStatus as follows:

CALL GetOrderCountByStatus('in process',@total);


SELECT @total AS total_in_process;

The INOUT parameter example

The following example demonstrates how to use an INOUT parameter in a stored procedure:

DELIMITER $$

CREATE PROCEDURE SetCounter(


INOUT counter INT,
IN inc INT
)
BEGIN
SET counter = counter + inc;
END$$

DELIMITER ;

In this example, the stored procedure SetCounter() accepts one INOUT parameter ( counter )
and one IN parameter ( inc ). It increases the counter ( counter ) by the value of specified by
the inc parameter.

These statements illustrate how to call the SetSounter stored procedure:

SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8

Here is the output:

MySQL Stored Procedure Variables

A variable is a named data object whose value can change during the stored
procedure execution. You typically use variables in stored procedures to hold immediate
results. These variables are local to the stored procedure.

Before using a variable, you must declare it.

Declaring variables

To declare a variable inside a stored procedure, you use the DECLARE statement as follows:

DECLARE variable_name datatype(size) [DEFAULT default_value];

In this syntax:

• First, specify the name of the variable after the DECLARE keyword. The variable name
must follow the naming rules of MySQL table column names.
• Second, specify the data type and length of the variable. A variable can have any MySQL
data types such as INT, VARCHAR , and DATETIME.
• Third, assign a variable a default value using the DEFAULT option. If you declare a
variable without specifying a default value, its value is NULL.

The following example declares a variable named totalSale with the data type DEC(10,2) and
default value 0.0 as follows:

DECLARE totalSale DEC(10,2) DEFAULT 0.0;

MySQL allows you to declare two or more variables that share the same data type using a
single DECLARE statement. The following example declares two integer variables x and y, and
set their default values to zero.

DECLARE x, y INT DEFAULT 0;


Assigning variables

Once a variable is declared, it is ready to use. To assign a variable a value, you use
the SET statement:

SET variable_name = value;

For example:

DECLARE total INT DEFAULT 0;


SET total = 10;

The value of the total variable is 10 after the assignment.

In addition to the SET statement, you can use the SELECT INTO statement to assign the result of
a query to a variable as shown in the following example:

DECLARE productCount INT DEFAULT 0;

SELECT COUNT(*)
INTO productCount
FROM products;

In this example:

• First, declare a variable named productCount and initialize its value to 0.


• Then, use the SELECT INTO statement to assign the productCount variable the number
of products selected from the products table.

Variable scopes

A variable has its own scope that defines its lifetime. If you declare a variable inside a stored
procedure, it will be out of scope when the END statement of stored procedure reaches.

When you declare a variable inside the block BEGIN END, it will be out of scope if the END is
reached.

MySQL allows you to declare two or more variables that share the same name in different
scopes. Because a variable is only effective in its scope. However, declaring variables with the
same name in different scopes is not good programming practice.

A variable whose name begins with the @ sign is a session variable. It is available and accessible
until the session ends.
Putting it all together

The following example illustrates how to declare and use a variable in a stored procedure:

DELIMITER //

CREATE PROCEDURE GetTotalOrder()


BEGIN
DECLARE totalOrder INT DEFAULT 0;

SELECT COUNT(*)
INTO totalOrder
FROM orders;

SELECT totalOrder;
END //

DELIMITER ;

Code language: SQL (Structured Query Language) (sql)

How it works.

First, declare a variable totalOrder with a default value of zero. This variable will hold the
number of orders from the orders table.

DECLARE totalOrder INT DEFAULT 0;

Second, use the SELECT INTO statement to assign the variable totalOrder the number of orders
selected from the orders table:

SELECT COUNT(*)
INTO totalOrder
FROM orders;

Third, select the value of the variable totalOrder.

SELECT totalOrder;

This statement calls the stored procedure GetTotalOrder():

CALL GetTotalOrder();

Here is the output:


Listing stored procedures using SHOW PROCEDURE STATUS statement

Here is the basic syntax of the SHOW PROCEDURE STATUS statement:

SHOW PROCEDURE STATUS [LIKE 'pattern' | WHERE search_condition]

The SHOW PROCEDURE STATUS statement shows all characteristic of stored procedures
including stored procedure names. It returns stored procedures that you have a privilege to
access.

The following statement shows all stored procedure in the current MySQL server:

SHOW PROCEDURE STATUS;


Code language: SQL (Structured Query Language) (sql)

Here is the partial output:

If you just want to show stored procedures in a particular database, you can use
a WHERE clause in the SHOW PROCEDURE STATUS as shown in the following statement:

SHOW PROCEDURE STATUS WHERE search_condition;

For example, this statement lists all stored procedures in the sample database classicmodels:

SHOW PROCEDURE STATUS WHERE db = 'classicmodels';

In case you want to find stored procedures whose names contain a specific word, you can use
the LIKE clause as follows:

SHOW PROCEDURE STATUS LIKE '%pattern%'

The following statement shows all stored procedure whose names contain the wordOrder:

SHOW PROCEDURE STATUS LIKE '%Order%'


MySQL IF Statement

The IF statement has three forms: simple IF-THEN statement, IF-THEN-ELSE statement, and IF-
THEN-ELSEIF- ELSE statement.

MySQL simple IF-THEN statement

The IF-THEN statement allows you to execute a set of SQL statements based on a specified
condition. The following illustrates the syntax of the IF-THEN statement:

IF condition THEN
statements;
END IF;

In this syntax:

• First, specify a condition to execute the code between the IF-THEN and END IF . If
the condition evaluates to TRUE, the statements between IF-THEN and END IF will execute.
Otherwise, the control is passed to the next statement following the END IF.
• Second, specify the code that will execute if the condition evaluates to TRUE.

We’ll use the customers table from the sample database for the demonstration:
See the following GetCustomerLevel() stored procedure.

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL(10,2) DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
END IF;
END$$

DELIMITER ;

The stored procedure GetCustomerLevel() accepts two


parameters: pCustomerNumber and pCustomerLevel.

• First, select creditLimit of the customer specified by the pCustomerNumber from


the customers table and store it in the local variable credit.
• Then, set value for the OUT parameter pCustomerLevel to PLATINUM if the credit limit of
the customer is greater than 50,000.

This statement finds all customers that have a credit limit greater than 50,000:
SELECT
customerNumber,
creditLimit
FROM
customers
WHERE
creditLimit > 50000
ORDER BY
creditLimit DESC;

Here is the partial output:

These statements call the GetCustomerLevel() stored procedure for customer 141 and show the
value of the OUT parameter pCustomerLevel:

CALL GetCustomerLevel(141, @level);


SELECT @level;

Because the customer 141 has a credit limit greater than 50,000, its level is set to PLATINUM as
expected.

MySQL IF-THEN-ELSE statement

In case you want to execute other statements when the condition in the IF branch does not
evaluate to TRUE, you can use the IF-THEN-ELSE statement as follows:

IF condition THEN
statements;
ELSE
else-statements;
END IF;
In this syntax, if the condition evaluates to TRUE, the statements between IF-
THEN and ELSE execute. Otherwise, the else-statements between the ELSE and END IF execute.

Let’s modify the GetCustomerLevel() stored procedure.

First, drop the GetCustomerLevel() stored procedure:

DROP PROCEDURE GetCustomerLevel;

Then, create the GetCustomerLevel() stored procedure with the new code:

DELIMITER //

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
ELSE
SET pCustomerLevel = 'NOT PLATINUM';
END IF;
END //

DELIMITER ;

In this new stored procedure, we include the ELSE branch. If the credit is not greater
than 50,000, we set the customer level to NOT PLATINUM in the block between ELSE and END
IF.

This query finds customers that have credit limit less than or equal 50,000:

SELECT
customerNumber,
creditLimit
FROM
customers
WHERE
creditLimit <= 50000
ORDER BY
creditLimit DESC;
This picture shows the partial output:

The following statements call the stored procedure for customer number 447 and show the
value of the OUT parameter pCustomerLevel:

CALL GetCustomerLevel(447, @level);


SELECT @level;

The credit limit of the customer 447 is less than 50,000, therefore, the statement in
the ELSE branch executes and sets the value of the OUT parameter pCustomerLevel to NOT
PLATINUM.

MySQL IF-THEN-ELSEIF-ELSE statement

If you want to execute statements conditionally based on multiple conditions, you use the
following IF-THEN-ELSEIF-ELSE statement:

IF condition THEN
statements;
ELSEIF elseif-condition THEN
elseif-statements;
...
ELSE
else-statements;
END IF;

In this syntax, if the condition evaluates to TRUE , the statements in the IF-THEN branch
executes; otherwise, the next elseif-condition is evaluated.

If the elseif-condition evaluates to TRUE, the elseif-statement executes; otherwise, the


next elseif-condition is evaluated.
The IF-THEN-ELSEIF-ELSE statement can have multiple ELSEIF branches.

If no condition in the IF and ELSE IF evaluates to TRUE, the else-statements in the ELSE branch
will execute.

We will modify the GetCustomerLevel() stored procedure to use the IF-THEN-ELSEIF-


ELSE statement.

First, drop the GetCustomerLevel() stored procedure:

DROP PROCEDURE GetCustomerLevel;

Then, create the new GetCustomerLevel() stored procedure that uses the the IF-THEN-ELSEIF-
ELSE statement.

DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
ELSEIF credit <= 50000 AND credit > 10000 THEN
SET pCustomerLevel = 'GOLD';
ELSE
SET pCustomerLevel = 'SILVER';
END IF;
END $$

DELIMITER ;

In this stored procedure:

• If the credit is greater than 50,000, the level of the customer is PLATINUM.
• If the credit is less than or equal 50,000 and greater than 10,000, then the level of
customer is GOLD.
• Otherwise, the level of the customer is SILVER.

These statements call the stored procedure GetCustomerLevel() and show the level of the
customer 447:
CALL GetCustomerLevel(447, @level);
SELECT @level;

If you test the stored procedure with the customer that has a credit limit of 10000 or less, you
will get the output as SILVER.

MySQL CASE Statement

Besides the IF statement, MySQL provides an alternative conditional statement called


the CASE statement for constructing conditional statements in stored procedures.
The CASE statements make the code more readable and efficient.

The CASE statement has two forms: simpleCASE and searched CASE statements.

Note that if you want to add the if-else logic to an SQL statement, you use
the CASE expression which is different from the CASE statement described in this tutorial.

Simple CASE statement

The following is the basic syntax of the simple CASE statement:

CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
END CASE;

In this syntax, the simple CASE statement sequentially compares the case_value is with
the when_value1, when_value2, … until it finds one is equal. When the CASE finds
a case_value equal to a when_value, it executes statements in the corresponding THEN clause.

If CASE cannot find any when_value equal to the case_value, it executes the else-statements in
the ELSE clause if the ELSE clause is available.

When the ELSE clause does not exist and the CASE cannot find any when_value equal to
the case_value, it issues an error:

Case not found for CASE statement


Note that the case_value can be a literal value or an expression. The statements can be one or
more SQL statements, and cannot have zero statements.

To avoid the error when the case_value does not equal any when_value, you can use an
empty BEGIN END block in the ELSE clause as follows:

CASE case_value
WHEN when_value1 THEN ...
WHEN when_value2 THEN ...
ELSE
BEGIN
END;
END CASE;

The simple CASE statement tests for equality ( =), you cannot use it to test equality with NULL;
because NULL = NULL returns FALSE.

Simple CASE statement example

The following stored procedure illustrates how to use the simple CASE statement:

DELIMITER $$

CREATE PROCEDURE GetCustomerShipping(


IN pCustomerNUmber INT,
OUT pShipping VARCHAR(50)
)
BEGIN
DECLARE customerCountry VARCHAR(100);

SELECT
country
INTO customerCountry FROM
customers
WHERE
customerNumber = pCustomerNUmber;

CASE customerCountry
WHEN 'USA' THEN
SET pShipping = '2-day Shipping';
WHEN 'Canada' THEN
SET pShipping = '3-day Shipping';
ELSE
SET pShipping = '5-day Shipping';
END CASE;
END$$

DELIMITER ;

How it works.
The GetCustomerShipping() stored procedure accepts two parameters: pCustomerNumber as
an IN parameter and pShipping as an OUT parameter.

In the stored procedure:

First, select the country of the customer from the customers table by the input customer
number.

Second, use the simple CASE statement to determine the shipping time based on the country of
the customer. If the customer locates in USA , the shipping time is 2-day shipping . If the
customer locates in Canada , the shipping time is 3-day shipping . The customers from other
countries have 5-day shipping .

The following flowchart demonstrates the logic of the CASE statement for determining the
shipping time:

This statement calls the stored procedure and passes the customer number 112:

CALL GetCustomerShipping(112,@shipping);

The following statement returns the shipping time of the customer 112:

SELECT @shipping;
Here is the output:

+----------------+
| @shipping |
+----------------+
| 2-day Shipping |
+----------------+
1 row in set (0.00 sec)

MySQL LOOP

Introduction to MySQL LOOP statement

The LOOP statement allows you to execute one or more statements repeatedly.

Here is the basic syntax of the LOOP statement:

[begin_label:] LOOP
statement_list
END LOOP [end_label]

The LOOP can have optional labels at the beginning and end of the block.

The LOOP executes the statement_list repeatedly. The statement_list may have one or more
statements, each terminated by a semicolon (;) statement delimiter.

Typically, you terminate the loop when a condition is satisfied by using the LEAVE statement.

This is the typical syntax of the LOOP statement used with LEAVE statement:

[label]: LOOP
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
END LOOP;

The LEAVE statement immediately exits the loop. It works like the break statement in other
programming languages like PHP, C/C++, and Java.

In addition to the LEAVE statement, you can use the ITERATE statement to skip the current loop
iteration and start a new iteration. The ITERATE is similar to the continue statement in PHP,
C/C++, and Java.
MySQL LOOP statement example

The following statement creates a stored procedure that uses a LOOP loop statement:

DROP PROCEDURE LoopDemo;

DELIMITER $$
CREATE PROCEDURE LoopDemo()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1;
SET str = '';

loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;

SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$

DELIMITER ;

In this example:

• The stored procedure constructs a string from the even numbers e.g., 2, 4, and 6.
• The loop_label before the LOOPstatement for using with
the ITERATE and LEAVE statements.
• If the value of x is greater than 10, the loop is terminated because of
the LEAVEstatement.
• If the value of the x is an odd number, the ITERATE ignores everything below it and
starts a new loop iteration.
• If the value of the x is an even number, the block in the ELSEstatement will build the
result string from even numbers.

The following statement calls the stored procedure:

CALL LoopDemo();

Here is the output:

+-------------+
| str |
+-------------+
| 2,4,6,8,10, |
+-------------+
1 row in set (0.01 sec)

Query OK, 0 rows affected (0.02 sec)

MySQL WHILE Loop

Introduction to MySQL WHILE loop statement

The WHILE loop is a loop statement that executes a block of code repeatedly as long as a
condition is true.

Here is the basic syntax of the WHILE statement:

[begin_label:] WHILE search_condition DO


statement_list
END WHILE [end_label]

In this syntax:

First, specify a search condition after the WHILE keyword.

The WHILE checks the search_condition at the beginning of each iteration.

If the search_condition evaluates to TRUE, the WHILE executes the statement_list as long as
the search_condition is TRUE.

The WHILE loop is called a pretest loop because it checks the search_condition before
the statement_list executes.

Second, specify one or more statements that will execute between the DO and END
WHILE keywords.

Third, specify optional labels for the WHILE statement at the beginning and end of the loop
construct.

The following flowchart illustrates the MySQL WHILE loop statement:


MySQL WHILE loop statement example

First, create a table namedcalendars which stores dates and derived date information such as
day, month, quarter, and year:

CREATE TABLE calendars(


id INT AUTO_INCREMENT,
fulldate DATE UNIQUE,
day TINYINT NOT NULL,
month TINYINT NOT NULL,
quarter TINYINT NOT NULL,
year INT NOT NULL,
PRIMARY KEY(id)
);

Second, create a new stored procedure to insert a date into the calendars table:

DELIMITER $$

CREATE PROCEDURE InsertCalendar(dt DATE)


BEGIN
INSERT INTO calendars(
fulldate,
day,
month,
quarter,
year
)
VALUES(
dt,
EXTRACT(DAY FROM dt),
EXTRACT(MONTH FROM dt),
EXTRACT(QUARTER FROM dt),
EXTRACT(YEAR FROM dt)
);
END$$

DELIMITER ;

Third, create a new stored procedure LoadCalendars() that loads a number of days starting
from a start date into the calendars table.

DELIMITER $$

CREATE PROCEDURE LoadCalendars(


startDate DATE,
day INT
)
BEGIN

DECLARE counter INT DEFAULT 1;


DECLARE dt DATE DEFAULT startDate;

WHILE counter <= day DO


CALL InsertCalendar(dt);
SET counter = counter + 1;
SET dt = DATE_ADD(dt,INTERVAL 1 day);
END WHILE;

END$$

DELIMITER ;

The stored procedure LoadCalendars() accepts two arguments:

• startDate is the start date inserted into the calendars table.


• day is the number of days that will be loaded starting from the startDate.

In the LoadCalendars() stored procedure:

First, declare a counter and dt variables for keeping immediate values. The default values
of counter and dt are 1 and startDate respectively.

Then, check if the counter is less than or equal day, if yes:


• Call the stored procedure InsertCalendar() to insert a row into the calendars table.
• Increase the counter by one. Also, increase the dt by one day using
the DATE_ADD() function.

The WHILE loop repeatedly inserts dates into the calendars table until the counter is equal
to day.

The following statement calls the stored procedure LoadCalendars() to load 31 days into
the calendars table starting from January 1st 2019.

CALL LoadCalendars('2019-01-01',31);

MySQL REPEAT Loop

The REPEAT statement executes one or more statements until a search condition is true.

Here is the basic syntax of the REPEAT loop statement:

[begin_label:] REPEAT
statement
UNTIL search_condition
END REPEAT [end_label]

The REPEAT executes the statement until the search_condition evaluates to true.
The REPEAT checks the search_condition after the execution of statement, therefore,
the statement always executes at least once. This is why the REPEAT is also known as a post-
test loop.

The REPEAT statement can have labels at the beginning and at the end. These labels are
optional.

The following flowchart illustrates the REPEAT loop:

MySQL REPEAT loop example

This statement creates a stored procedure called RepeatDemo that uses the REPEAT statement
to concatenate numbers from 1 to 9:

DELIMITER $$

CREATE PROCEDURE RepeatDemo()


BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE result VARCHAR(100) DEFAULT '';

REPEAT
SET result = CONCAT(result,counter,',');
SET counter = counter + 1;
UNTIL counter >= 10
END REPEAT;
-- display result
SELECT result;
END$$

DELIMITER ;

In this stored procedure:

First, declare two variables counter and result and set their initial values to 1 and blank.

The counter variable is used for counting from 1 to 9 in the loop. And the result variable is used
for storing the concatenated string after each loop iteration.

Second, append counter value to the result variable using the CONCAT() function until
the counter is greater than or equal to 10.

The following statement calls the RepeatDemo() stored procedure:

CALL RepeatDemo();

Here is the output:

+--------------------+
| result |
+--------------------+
| 1,2,3,4,5,6,7,8,9, |
+--------------------+
1 row in set (0.02 sec)

Query OK, 0 rows affected (0.02 sec)

MySQL LEAVE

Introduction to MySQL LEAVE statement

The LEAVE statement exits the flow control that has a given label.

The following shows the basic syntax of the LEAVE statement:

LEAVE label;

In this syntax, you specify the label of the block that you want to exit after the LEAVE keyword.
Using the LEAVE statement to exit a stored procedure

If the label is the outermost of the stored procedure or function block, LEAVE terminates the
stored procedure or function.

The following statement shows how to use the LEAVE statement to exit a stored procedure:

CREATE PROCEDURE sp_name()


sp: BEGIN
IF condition THEN
LEAVE sp;
END IF;
-- other statement
END$$

For example, this statement creates a new stored procedure that checks the credit of a given
customer in the customers table from the sample database:

DELIMITER $$

CREATE PROCEDURE CheckCredit(


inCustomerNumber int
)
sp: BEGIN

DECLARE customerCount INT;

-- check if the customer exists


SELECT
COUNT(*)
INTO customerCount
FROM
customers
WHERE
customerNumber = inCustomerNumber;

-- if the customer does not exist, terminate


-- the stored procedure
IF customerCount = 0 THEN
LEAVE sp;
END IF;

-- other logic
-- ...
END$$

DELIMITER ;

Using LEAVE statement in loops

The LEAVE statement allows you to terminate a loop. The general syntax for
the LEAVE statement when using in the LOOP, REPEAT and WHILE statements.

Using LEAVE with the LOOP statement:

[label]: LOOP
IF condition THEN
LEAVE [label];
END IF;
-- statements
END LOOP [label];

Using LEAVE with the REPEAT statement:

[label:] REPEAT
IF condition THEN
LEAVE [label];
END IF;
-- statements
UNTIL search_condition
END REPEAT [label];

Using LEAVE with the WHILE statement:

[label:] WHILE search_condition DO


IF condition THEN
LEAVE [label];
END IF;
-- statements
END WHILE [label];

The LEAVE causes the current loop specified by the label to be terminated. If a loop is enclosed
within another loop, you can break out of both loops with a single LEAVE statement.
Using LEAVE statement in a loop example

The following stored procedure generates a string of integer with the number from 1 to a
random number between 4 and 10:

DELIMITER $$

CREATE PROCEDURE LeaveDemo(OUT result VARCHAR(100))


BEGIN
DECLARE counter INT DEFAULT 1;
DECLARE times INT;
-- generate a random integer between 4 and 10
SET times = FLOOR(RAND()*(10-4+1)+4);
SET result = '';
disp: LOOP
-- concatenate counters into the result
SET result = concat(result,counter,',');

-- exit the loop if counter equals times


IF counter = times THEN
LEAVE disp;
END IF;
SET counter = counter + 1;
END LOOP;
END$$

DELIMITER ;

This statement calls the LeaveDemo procedure:

CALL LeaveDemo(@result);
SELECT @result;

Here is one of the outputs:

+------------------+
| @result |
+------------------+
| 1,2,3,4,5,6,7,8, |
+------------------+
1 row in set (0.00 sec)

You might also like