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

后端 未结 4 939
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 ;
    

提交回复
热议问题