0% found this document useful (0 votes)
55 views

Loops in MySQL

The document discusses various loop structures in MySQL including LOOP, WHILE, REPEAT, and IF-THEN-ELSE statements. It provides the syntax and usage of each loop with examples. LOOP runs a block of code repeatedly until a condition is met. WHILE checks a condition before each iteration. REPEAT executes code once then checks a condition. IF-THEN-ELSE and IF-THEN-ELSEIF-ELSE allow for conditional execution of code blocks. The examples demonstrate how to use these loops to iterate through data and perform conditional logic.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Loops in MySQL

The document discusses various loop structures in MySQL including LOOP, WHILE, REPEAT, and IF-THEN-ELSE statements. It provides the syntax and usage of each loop with examples. LOOP runs a block of code repeatedly until a condition is met. WHILE checks a condition before each iteration. REPEAT executes code once then checks a condition. IF-THEN-ELSE and IF-THEN-ELSEIF-ELSE allow for conditional execution of code blocks. The examples demonstrate how to use these loops to iterate through data and perform conditional logic.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

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

• 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 ;
LOOP,LEAVE,ITERATE Example
• 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.
LOOP,LEAVE,ITERATE Example
• The following statement calls the stored
procedure:
• CALL LoopDemo();
• Output
• Here is the output:
• 2,4,6,8,10,
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]
WHILE loop statement
• 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.
WHILE loop statement
• 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:
WHILE loop statement
WHILE loop statement
Example
• First, create a table named calendars 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) );
WHILE loop statement
Example
• 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 ;
WHILE loop statement
Example
• Third, create a new stored procedure
LoadCalendars() that loads a number of days
starting from a start date into the calendars
table.

WHILE loop statement
Example
• 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
WHILE loop statement
Example
• 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.
• CALL LoadCalendars('2019-01-01',31);
WHILE loop statement
Example
• Output
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]
REPEAT Loop

• 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.
REPEAT loop
REPEAT loop example

• This statement creates a stored procedure


called RepeatDemo  that uses the REPEAT
statement to concatenate numbers from 1 to
9:
• ;
REPEAT loop 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

• 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;
IF-THEN-ELSE statement
• 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.
IF-THEN-ELSE statement Example
• 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 ;
IF-THEN-ELSE statement Example
• 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.
IF-THEN-ELSE statement Example
• 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;
IF-THEN-ELSE statement Example
• This picture shows the partial output:
IF-THEN-ELSE statement Example
• CALL GetCustomerLevel(447, @level);
• SELECT @level;
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;
IF-THEN-ELSEIF-ELSE statement example
• 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 ;
IF-THEN-ELSEIF-ELSE statement example

• 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.
IF-THEN-ELSEIF-ELSE statement example

• CALL GetCustomerLevel(447, @level); SELECT


@level;
CASE Expression
• 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.
CASE Expression
• 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;
CASE Expression
• 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 statement example

• 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

You might also like