Duration: 2 hours (Lecture: 2 hours, Lab: 2 hours)
Syllabus Topics:
MySQL stored procedures support flow control statements to manage the execution flow, enabling loops and iterative processing.
A basic looping construct that continues until explicitly terminated with LEAVE
or RETURN
.
Syntax:
[label]: LOOP
-- Statements
IF condition THEN
LEAVE [label];
END IF;
END LOOP [label];
Example: Iterate to insert numbers 1 to 5 into a table.
CREATE PROCEDURE InsertNumbers()
BEGIN
DECLARE counter INT DEFAULT 1;
my_loop: LOOP
INSERT INTO numbers (value) VALUES (counter);
SET counter = counter + 1;
IF counter > 5 THEN
LEAVE my_loop;
END IF;
END LOOP my_loop;
END;
Key Notes:
LEAVE
statement to avoid infinite loops.Executes a block of statements as long as a condition is true, checked before each iteration.
Syntax:
WHILE condition DO
-- Statements
END WHILE;
Example: Insert even numbers up to 10.
CREATE PROCEDURE InsertEvenNumbers()
BEGIN
DECLARE num INT DEFAULT 2;
WHILE num <= 10 DO
INSERT INTO numbers (value) VALUES (num);
SET num = num + 2;
END WHILE;
END;
Key Notes:
Executes statements until a condition becomes true, checked after each iteration (at least one iteration is guaranteed).
Syntax:
REPEAT
-- Statements
UNTIL condition
END REPEAT;
Example: Insert odd numbers up to 9.
CREATE PROCEDURE InsertOddNumbers()
BEGIN
DECLARE num INT DEFAULT 1;
REPEAT
INSERT INTO numbers (value) VALUES (num);
SET num = num + 2;
UNTIL num > 9
END REPEAT;
END;
Key Notes:
WHILE
.INSERT
/UPDATE
).WHILE
loop.Conditional statements control the execution path based on conditions.
IF:
Executes a block of code if a condition is true.
Syntax:
IF condition THEN
-- Statements
END IF;
Example: Increase salary if above a threshold.
IF salary > 50000 THEN
SET salary = salary * 1.1;
END IF;
IF-ELSE-THEN:
Executes one block if the condition is true, another if false.
Syntax:
IF condition THEN
-- Statements for true
ELSE
-- Statements for false
END IF;
Example: Adjust salary based on department.
IF dept_id = 1 THEN
SET salary = salary * 1.1;
ELSE
SET salary = salary * 1.05;
END IF;
SWITCH CASE:
Evaluates a value and executes the corresponding block.
Syntax:
CASE expression
WHEN value1 THEN
-- Statements
WHEN value2 THEN
-- Statements
ELSE
-- Default statements
END CASE;
Alternative Syntax (condition-based):
CASE
WHEN condition1 THEN
-- Statements
WHEN condition2 THEN
-- Statements
ELSE
-- Default statements
END CASE;
Example: Assign bonus based on department.
CASE dept_id
WHEN 1 THEN SET bonus = 1000;
WHEN 2 THEN SET bonus = 500;
ELSE SET bonus = 200;
END CASE;