Loop Mysql to insert data in table using PhpMyadmi

2019-06-06 11:13发布

问题:

Hi im trying to insert data in a database for asign an id to each number

table numbers

id | number

1  | 2560
2  | 2561

And this go on for 100 numbers. i found this for PL/sql

BEGIN
   FOR v_LoopCounter IN 2560..2660 LOOP
   INSERT INTO numbers (number)
   VALUES (v_LoopCounter);
END LOOP;
END;

Also tried like

BEGIN
   FOR v_LoopCounter IN 2560.2660 LOOP;
   INSERT INTO numbers (number);
   VALUES (v_LoopCounter);
END LOOP;
END;

How can i do this in Sql using Phpmyadmin, for thats what i can use.

Thanks!

I have tried to run this SQL in PHPMyadmin, but i always got a Syntax Error

There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

I also have tried now

SELECT * FROM table_name WHERE
BEGIN
       FOR v_LoopCounter IN 2560..2660 LOOP
       INSERT INTO numbers (number)
       VALUES (v_LoopCounter);
    END LOOP;
    END;

回答1:

Try :

DELIMITER //
BEGIN
   FOR v_LoopCounter IN 2560..2660 LOOP
   INSERT INTO numbers (number)
   VALUES (v_LoopCounter);
END LOOP;
END
//


回答2:

Try this SELECT a database first else you will get the no database selected error

DROP PROCEDURE IF EXISTS myFunction;
delimiter $$

CREATE PROCEDURE myFunction()
     BEGIN
             DECLARE i INT DEFAULT 1;
             DECLARE j INT DEFAULT 0;
             DROP TABLE IF EXISTS test;
             CREATE TEMPORARY TABLE test
                 (id int, numbers int);

         WHILE (i<=100) DO
                SET j=i+2560;
                INSERT INTO test VALUES(i,j);
                SET i=i+1;
         END WHILE;

         select * from test;

         drop table test;

 END$$

After that call the procedure

delimiter ;

call myFunction();