Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 761
Mr. Boy Avatar asked Feb 06 '13 22:02

Mr. Boy


People also ask

Can we write LOOP in MySQL?

You can also create functions in MYSQL. Similar to other programming languages MySQL provides support for the flow control statements such as IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT. You can use these statements in the stored programs (procedures), and RETURN in stored functions.

Can we use looping in stored procedure?

The LOOP statement allows you to execute one or more statements repeatedly. The LOOP can have optional labels at the beginning and end of the block. The LOOP executes the statement_list repeatedly. The statement_list may have one or more statements, each terminated by a semicolon (;) statement delimiter.


1 Answers

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 ; 
like image 75
Thanu Avatar answered Sep 20 '22 11:09

Thanu