Answer: Conditional Logic and Loops
Explore how to create stored procedures using variables, loops, and conditional statements in MySQL. This lesson helps you understand iterative processing with WHILE loops and IF conditions to classify data and manage row-by-row operations within routines.
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Line 1: Switch the statement delimiter so the routine body can contain semicolons safely.
Line 3: Drop the procedure if it already exists so the new definition can be created cleanly.
Line 4: Create the procedure
LoopClassifySuppliers.Line 5: Start the block with
BEGIN, which defines the scope for all declarations and executable statements inside the procedure.Lines 6–11: Declare a loop counter
i, a total row counttotal, and per-row variables for supplier fields.Lines 14–19: Create a temporary table
SupplierAuditif it does not already exist. This session-scoped table stores each supplier’s classification results.Lines 22–24: Count all suppliers and store that count in
total.Lines 27–33: Start a
WHILEloop that runs untilireachestotal. Each iteration fetches the i-th supplier usingORDER BYplusLIMIT i, 1, and assigns values into variables with ...