MySQL loop control

Source: Internet
Author: User

1. Using while
DROP PROCEDURE IF EXISTS ' addstudent ';
DELIMITER;;
CREATE PROCEDURE ' addstudent ' (iNum int)
BEGIN
DECLARE VI int default 0;

Start transaction;

while (VI < iNum) do
INSERT into student (Id,name) VALUES (Vi,concat (' Andy ', VI));
Set VI = vi+1;
End while;

Commit
END
;;
DELIMITER;
2. Using repeat
BEGIN
DECLARE VI int default 0;

Start transaction;

Repeat
INSERT into student (Id,name) VALUES (Vi,concat (' Andy ', VI));
Set VI = vi+1;
Until VI >= INum end repeat;

Commit
END


3. Using loop
BEGIN
DECLARE VI int default 0;

Start transaction;

Label_insert:loop

INSERT into student (Id,name) VALUES (Vi,concat (' Andy ', vi));
Set VI = vi+1;
if (VI >= iNum) Then
Leave Label_insert;
End If;

End LOOP Label_insert;

Commit
END
4, consider the following requirements, in the programming language in the loop control has continue, how to achieve the function of continue?
Use iterate Label_insert; For Loop as follows:
BEGIN
DECLARE VI int default 0;

Start transaction;

Label_insert:loop

if (vi=2) then
Set VI = vi+1;
Iterate Label_insert;
End If;

INSERT into student (Id,name) VALUES (Vi,concat (' Andy ', vi));
Set VI = vi+1;
if (VI >= iNum) Then
Leave Label_insert;
End If;

End LOOP Label_insert;

Commit
END

Note: The same is true for while and repeat, but you need to add a label in front of the while and repeat to indicate the position of the loop again, as follows:
Label_insert:while
Label_insert:repeat
There is currently no for loop in MySQL.

MySQL loop control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.