1. While Loop
DELIMITER $$DROP PROCEDURE IF EXISTS' Sp_test_while ' $$CREATE PROCEDURE' Sp_test_while ' (inchP_numberINT, #要循环的次数inchP_startidINT#循环的其实值)BEGIN DECLAREV_valINT DEFAULT 0; SETV_val=P_startid;outer_label:BEGIN#设置一个标记 whileV_val<=P_number DoSETV_val=V_val+1; IF(V_val= -) ThenLEAVE Outer_label; #满足条件, terminates the loop, jumps to the end Outer_label tagEND IF;END while; SELECT 'I'm the while outside, the SQL inside the Outer_label'#由于这句SQL在outer_label代码块内, so level, this SQL will not execute, #只要是在outer_label代码块内 anywhere Leave Outer_label, then the Leave code will no longer execute ENDOuter_label; SELECTCONCAT ('Test', V_val) asTname;END$ $DELIMITER; Call Sp_test_while ( +,0);
2, Loop loop
DELIMITER $$DROP PROCEDURE IF EXISTS' Sp_testloop ' $$CREATE PROCEDURE' Sp_testloop ' (inchP_numberINT, #要循环的次数inchP_startidINT#循环的其实值)BEGIN DECLAREV_valINT DEFAULT 0; SETV_val=P_startid; Loop_label:loop #循环开始SETV_val=V_val+1; IF(V_val>P_number) ThenLEAVE Loop_label; #终止循环END IF; ENDLOOP; SELECTCONCAT ('Testloop_', V_val) asTname;END$ $delimiter; Call Sp_testloop ( +,0);
3. Repeat cycle
DELIMITER $$DROP PROCEDURE IF EXISTS' sp_test_repeat ' $$CREATE PROCEDURE' Sp_test_repeat ' (inchP_numberINT, #要循环的次数inchP_startidINT#循环的其实值)BEGIN DECLAREV_valINT DEFAULT 0; SETV_val=P_startid; REPEAT #repeat循环开始SETV_val=V_val+1; Until V_val>P_number #终止循环的条件, Note that it is not possible to use '; ' Semicolon, otherwise error ENDrepeat; #循环结束SELECTCONCAT ('Test', V_val) asTname;END$ $DELIMITER; Call Sp_test_repeat ( +,0);
MySQL While,loop,repeat loop, eligible to jump out of the loop