MySQL Loop

MySQL Loop

MySQL Loop syntax and example.

MySQL Loop syntax

[ begin_label: ] LOOP
statement_list
END LOOP [ end_label ]

Loop example

CREATE PROCEDURE loop_proc(x INT)
BEGIN
DECLARE p_output VARCHAR(50);
SET p_output = '';
  loop_label: LOOP
	SET p_output = CONCAT(p_output,x,',');
    SET x = x + 1;
    IF x <= 5 THEN
      ITERATE loop_label;
    END IF;
    LEAVE loop_label;
  END LOOP loop_label;
  SELECT p_output;
END;

CALL loop_proc(1);

Output

PROCEDURE LOOP_PROC compiled
p_output
1,2,3,4,5,