Loops in MySQL
Loops in MySQL
Loops
• The MySQL LOOP statement could be used to run a
block of code or set of statements, again and again,
depends on the condition.
• Syntax :
• [labelname:] LOOP statements END LOOP [labelname]
• Parameters –
• labelname : It is an optional label at the start and end.
• statements : They could have one or multiple
statements, each ended by a semicolon (;) and executed
by LOOP.
LOOP,LEAVE,ITERATE
• 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;
LOOP,LEAVE,ITERATE
• 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.
LOOP,LEAVE,ITERATE example
• 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
REPEAT loop example
• Here is the output:
• 1,2,3,4,5,6,7,8,9,
IF-THEN-ELSE 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 ;
Thank You