Name
LOOP-04: Use a simple loop to avoid redundant code required by a WHILE or REPEAT UNTIL loop
Synopsis
This guideline is particularly relevant when you are writing cursor loops.
The structure of MySQL cursors, and the necessity of setting an indicator variable to detect the end of the cursor, means that you usually want to execute the cursor loop at least once. You will then continue executing the loop until the indicator variable changes.
This sounds like a perfect opportunity to apply the REPEAT UNTIL loop. So as you start to
create the program, you create a structure that looks like
this:
DECLARE dept_csr CURSOR FOR
SELECT department_name
FROM departments;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_departments=1;
OPEN dept_csr;
REPEAT
FETCH dept_csr INTO v_department_name;
UNTIL (no_more_departments) END REPEAT;
CLOSE dept_csr;
SET no_more_departments=0;Of course, you always want to do something with the data
fetched from a cursor, but you need to make sure that you don't
try to process data after the last row has been returned. So in
order to keep the REPEAT loop,
you create an IF structure to
enclose your processing:
DECLARE dept_csr CURSOR FOR
SELECT department_name
FROM departments;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_departments=1;
OPEN dept_csr;
REPEAT
FETCH dept_csr INTO v_department_name;
IF (no_more_departments=0) THEN
SET v_count= v_count+1;
END IF;
UNTIL (no_more_departments) END REPEAT;
CLOSE dept_csr;
SET no_more_departments=0;The problem with ...