0

I have this code for insert rows to table. I have three while nesthed themself, but this code give me

error #1064 - bad syntax  close

    BEGIN
            WHILE p <= 5
            BEGIN
                WHILE ra <= 40
            ' on line 7.

What is wrong with this code?

 DELIMITER $$

CREATE PROCEDURE proc()
BEGIN
    DECLARE r int DEFAULT 1;
    DECLARE p int DEFAULT 1;
    DECLARE ra int DEFAULT 1;
    WHILE r <= 8 DO

        WHILE p <= 5 DO

            WHILE ra <= 40 DO

                INSERT INTO tabulka (REGAL,POLICE,RADA) VALUES(r,p,ra);
                SET ra = ra + 1;
            END WHILE;
            SET p = p + 1;
        END WHILE;
        SET r = r + 1;
    END WHILE;
END$$
DELIMITER ;

CALL proc();

enter image description here

EDIT: Now it generates only one loop: enter image description here

2 Answers 2

3

MySQL uses WHILE DO/END WHILE for it syntax. So the stored procedure should look like this:

CREATE PROCEDURE proc()
BEGIN
    DECLARE r int DEFAULT 1;
    DECLARE p int DEFAULT 1;
    DECLARE ra int DEFAULT 1;
    WHILE r <= 8 DO
        WHILE p <= 5 DO
            WHILE ra <= 40 DO
                INSERT INTO tabulka (REGAL,POLICE,RADA) VALUES(r,p,ra);
                SET ra = ra + 1;
            END WHILE;
            SET p = p + 1;
        END WHILE;
        SET r = r + 1;
    END WHILE;
END;

Here is a little rextester.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but now it only generates 40 rows with regal = 1, police = 1 and rada = 1 .... 40, but i want to generate regal 1-8 and rada 1-5
@adam . . . This is your code with the syntax errors fixed -- which is the question you asked. If you have another question about logic, ask it as a new question. That said, I suspect your problem is that you do not re-initialize the variable before restarting each loop.
0

Okay, my mistake. I forgot to reset variables to 1 after inside loops was done. Thanks for help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.