Pregunta

Ok this might be ridiculous but I've been scratching my head for quite a few minutes now. What is wrong with this syntax?

SET @maxIterations = 10;
SET @i = 0;

myloop: LOOP
    SET @i = @i + 1;

    UPDATE `mytable`
    SET `field` = 'value';

    if @i < @maxIterations THEN ITERATE myloop; END IF;

    LEAVE myloop;
END LOOP myloop;

I am getting error near 'myloop: LOOP SET i = i + 1' at line 1

¿Fue útil?

Solución

Your syntax is generally correct, except that MySQL does not permit flow control structures like IF/ELSE, WHILE, LOOP in anything other than a stored procedure or function ("stored programs"). This limitation is documented here:

MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT constructs for flow control within stored programs. It also supports RETURN within stored functions.

You will be able to correctly create this as a stored procedure, as in:

DELIMITER $$
CREATE PROCEDURE myproc()
BEGIN
  SET @maxIterations = 10;
  SET @i = 0;

  myloop: LOOP
      SET @i = @i + 1;

      UPDATE `mytable`
      SET `field` = 'value';

      if @i < @maxIterations THEN ITERATE myloop; END IF;

      LEAVE myloop;
  END LOOP myloop;
END$$
DELIMITER ;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top