MySQL Insert with While Loop

后端 未结 2 1450
误落风尘
误落风尘 2020-12-13 02:32

I\'m trying to create a bunch of records in my MySQL database. This is a one time creation so I am not trying to create a stored procedure. Here is my code:



        
相关标签:
2条回答
  • 2020-12-13 02:55
    drop procedure if exists doWhile;
    DELIMITER //  
    CREATE PROCEDURE doWhile()   
    BEGIN
    DECLARE i INT DEFAULT 2376921001; 
    WHILE (i <= 237692200) DO
        INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
        SET i = i+1;
    END WHILE;
    END;
    //  
    
    CALL doWhile(); 
    
    0 讨论(0)
  • 2020-12-13 03:03

    You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

    You have to put your code in a stored procedure. Example:

    CREATE PROCEDURE myproc()
    BEGIN
        DECLARE i int DEFAULT 237692001;
        WHILE i <= 237692004 DO
            INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
            SET i = i + 1;
        END WHILE;
    END
    

    Fiddle: http://sqlfiddle.com/#!2/a4f92/1

    Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

    for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done
    

    By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

    0 讨论(0)
提交回复
热议问题