Skip to content

What's Aurora MySQL WHILE - DO statement correct syntax?

0

I am trying to create a WHILE loop in Aurora MySQL. With this syntax:

SET @inc = 0;

WHILE @inc <= 5 DO SET @inc = @inc + 1; END;

I getting syntax error near 'WHILE @inc <= 5 DO

What's the correct syntax in Aurora MySQL?

My AURORA_VERSION() is 2.10.0

Thanks

asked 4 years ago993 views
3 Answers
1
Accepted Answer

You need to add a delimiter as explained here

The following works for me when I test it on Aurora MySQL 2.10.0:

delimiter //
CREATE PROCEDURE dowhile()
  BEGIN
   DECLARE v1 INT DEFAULT 5;
    WHILE v1 > 0 DO
     SET v1 = v1 - 1;
   END WHILE;
 END; //
delimiter ;
AWS
answered 4 years ago
EXPERT
reviewed 4 years ago
  • Thanks. This solved it. Just want to point out that DELIMITER is needed with some clients. Is not a feature of Aurora or MySQL. For instance when I call the query using PyMySQL, I need to remove them.

1

According to this answer on Stack Overflow, you can only use WHILE if you're inside a stored program or function body.


EDIT: Shiv has correctly identified the problem in relation to a missing delimiter reassignment. A good explanation of why the delimiter is sometimes necessary is given in the MySQL docs:

If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.

The example uses // as a temporary delimiter, but any character or multiple characters (except backslash) can be used, for example $$ is commonly seen. The idea is to nest the stored program inside a pair of delimiter statements:

delimiter $$          -- <- set delimiter temorarily to $$
/* stored program definition goes here, including semicolons */
delimeter;            -- <- restore delimiter to default (semicolon)
answered 4 years ago
0

WHILE statement is part of Flow Control Statements

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

answered 4 years ago
  • Yes. From there I took this sample:

    CREATE PROCEDURE dowhile() BEGIN DECLARE v1 INT DEFAULT 5;

    WHILE v1 > 0 DO SET v1 = v1 - 1; END WHILE; END;

    I and get this error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3

    None of the samples I found works.

    Thanks.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.