27

For testing, is it possible to run a loop from MySQL workbench or similar tool? I tried but got an error.

If it is possible, please supply a simple example I can run.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

4 Answers4

23

You can't do a for loop in an SQL editor without a stored procedure. I use TOAD for MySQL.

A quick stored procedure should do the job:

DELIMITER $$

DROP PROCEDURE IF EXISTS proc_loop_test$$
CREATE PROCEDURE proc_loop_test()
BEGIN
  DECLARE int_val INT DEFAULT 0;
  test_loop : LOOP
    IF (int_val = 10) THEN
      LEAVE test_loop;
    END IF;

    SET int_val = int_val +1;
    SELECT int_val; 
  END LOOP; 
END$$

DELIMITER ;
informatik01
  • 16,038
  • 10
  • 74
  • 104
Thanu
  • 2,481
  • 8
  • 34
  • 53
  • 2
    OK. After over an hour of testing, I ended up with: "_At `CREATE PROCEDURE proc_loop_test() BEGIN DECLARE int_val INT DEFAULT 0;` MySQL said: `#1064 - 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`_". What am I missing? – trejder Apr 02 '15 at 13:37
  • Sorry, I cant say whats really wrong without seeing your exact full proc code. Because it can be just a missing semicolon. – Thanu Apr 03 '15 at 01:47
  • 6
    had the same problem. Resolved it by changing the delimiter before the procedure to `$$` and changing it back to `;` afterwards. More info: http://www.mysqltutorial.org/stored-procedures-loop.aspx – Chris Apr 06 '16 at 13:02
4

There's a trick with limited use-cases that is "loop-like".

I wanted to create a large (1~2 million) row table of random integers for a test:

INSERT INTO test_table (num) VALUES(ROUND(RAND() * 1E6));

-- calling this will insert once for every row in test_table
INSERT INTO test_table (num)
SELECT ROUND(RAND() * 1E6)
FROM test_table;

So I quickly just kept doubling the number of rows until I had what I needed.

Kache
  • 15,647
  • 12
  • 51
  • 79
1

Supposed that you already have an arbitrary table myOldTable which is sufficiently long you could use the following trick:

set @counter = 0;
select (@counter := @counter+1), @counter*@counter from myOldTable limit 1000;
0

If it is that you only want to block the current thread then use select sleep(seconds); otherwise you can use a stored procedure (if there's something you want to loop over) or a UDF (user defined function).

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181