MySQL loop

  mysql three common cycle ways: while, repeat and loop cycle. There is also a goto, not recommended.

1.while cycle

 

- Set mysql separator is //, which means that when the next encounter a //, the overall execution of SQL statements 
DELIMITER // 

DROP PROCEDURE IF EXISTS 'test'; # test if there is a stored procedure is deleted 
CREATE procedure test () # Create no parameters stored procedure, entitled Test 
the BEGIN 
the dECLARE i the INT; # declare variable 
SET i = 0; # variable assignment 
wHILE i <5 DO # end of the cycle conditions: out of the while loop 5 when i is greater than 
INSERT INTO test VALUES (i + 11, 'test ', '20'); # to the test table to add data 
SET i = i + 1; # cycle time, i add. 1 
the eND the wHILE; # end of while loop 
SELECT * FROM test; # View test table data 
the eND 
// # define end statement 
cALL test (); # call a stored procedure 
dELIMITER; # again to the separator;

 

 

 

2.repeat cycle

// DELIMITER 
the DROP PROCEDURE the IF EXISTS test; 
the CREATE PROCEDURE test () 
the BEGIN 
  the DECLARE I the INT; 
  SET I = 0; 
  the REPEAT 
    the INSERT the INTO test the VALUES (I +. 11, 'test', '20 is'); # add data to the test table 
    SET i = i + 1; # cycle time, i add a 
  UNTIL i> 10 eND rEPEAT; # end of the cycle conditions: out of a repeat loop when i is greater than 10 
  the SELECT * the FROM Test; 
the eND 
// 
the CALL Test (); 
DELIMITER;

  

3.loop cycle

// DELIMITER 
the DROP the IF EXISTS PROCEDURE Test; 
the CREATE PROCEDURE Test () 
the BEGIN 
  the DECLARE the INT I; 
  the SET I = 0; 
	LP: is the loop LOOP # LP name, a keyword may be arbitrarily loop 
		INSERT INTO test VALUES (i + 11 , ' test ',' 20 '); # to the test table to add data 
		SET i = i + 1; # cycle time, i plus an 
		iF i> 10 THEN # end of the cycle conditions: out of loop cycles when i is greater than 10 
					the LEAVE LP; 
			the IF the END; 
	the END LOOP; 
	the SELECT * the FROM Test; 
the END 
// 
the CALL Test (); 
DELIMITER;

  

Guess you like

Origin www.cnblogs.com/smartsmile-yxh/p/11546901.html