SQL-插入时三重嵌套

时间:2019-03-23 11:25:41

标签: mysql sql database sql-insert

我有这段代码可以将行插入表中。我自己有三个,但这段代码给了我

error #1064 - bad syntax  close

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

此代码有什么问题?

 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

编辑:现在,它仅生成一个循环: enter image description here

2 个答案:

答案 0 :(得分:3)

MySQL对其语法使用WHILE DO / END WHILE。因此,存储过程应如下所示:

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;

这里有些rextester

答案 1 :(得分:0)

好的,我的错。我忘了在内部循环完成后将变量重置为1。感谢您的帮助。