문제

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

도움이 되었습니까?

해결책

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 ;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top