Can I run a loop in MySQL without using a procedure/function?

后端 未结 4 937
Happy的楠姐
Happy的楠姐 2021-02-18 13:39

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.

相关标签:
4条回答
  • 2021-02-18 14:20

    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 ;
    
    0 讨论(0)
  • 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 讨论(0)
  • 2021-02-18 14:30

    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.

    0 讨论(0)
  • 2021-02-18 14:31

    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).

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