• ADADADADAD

    MySQL流程控制之while、repeat、loop循环实例分析[ mysql数据库 ]

    mysql数据库 时间:2024-11-25 14:52:26

    作者:文/会员上传

    简介:

    前言循环是一段在程序中只出现一次,但可能会连续运行多次的代码。循环中的代码会运行特定的次数,或者是运行到特定条件成立时结束循环。循环分类:whilerepeatloop循环控制:lea

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    前言

      循环是一段在程序中只出现一次,但可能会连续运行多次的代码。

      循环中的代码会运行特定的次数,或者是运行到特定条件成立时结束循环。

      循环分类:

        while

        repeat

        loop

        循环控制:

        leave 类似于 break,跳出,结束当前所在的循环

        iterate类似于 continue,继续,结束本次循环,继续下一次

        while循环
        【标签:】while循环条件do循环体;endwhile【标签】;
        --创建测试表createtableuser(uidintprimary_key,usernamevarchar(50),passwordvarchar(50));
        ---------存储过程-whiledelimiter$$createprocedureproc16_while1(ininsertcountint)begindeclareiintdefault1;label:whilei<=insertcountdoinsertintouser(uid,username,`password`)values(i,concat('user-',i),'123456');seti=i+1;endwhilelabel;end$$delimiter;callproc16_while(10);

        存储过程语法是固定的:delimiter $$ create peocedure 循环名(参数)begin 代码 end $$ delimiter;

        注意在写循环体的时候,必须要要有定义循环的初识变量,采用declare i int default 默认值

        然后就是dlabel:while 判断条件 do 循环体 end while label; end && 必须要有

        ---------存储过程-while+leavetruncatetableuser;delimiter$$createprocedureproc16_while2(ininsertcountint)begindeclareiintdefault1;label:whilei<=insertcountdoinsertintouser(uid,username,`password`)values(i,concat('user-',i),'123456');ifi=5thenleavelabel;endif;seti=i+1;endwhilelabel;end$$delimiter;callproc16_while2(10);

        如果在内部需要跳出循环的话,采用if 判断 ,但是最后需要end if 结尾

        这里的leave就是 跳出循环,相对于break

        ---------存储过程-while+iteratetruncatetableuser;delimiter$$createprocedureproc16_while3(ininsertcountint)begindeclareiintdefault1;label:whilei<=insertcountdoseti=i+1;ifi=5theniteratelabel;endif;insertintouser(uid,username,`password`)values(i,concat('user-',i),'123456');endwhilelabel;end$$delimiter;callproc16_while3(10);

        这里的iterate 相对于continue 遇到就不执行下面的代码

        repeat循环
        repeat循环体;until条件表达式endrepeat[标签];
        ---------存储过程-循环控制-repeatusemysql7_procedure;truncatetableuser;delimiter$$createprocedureproc18_repeat(ininsertCountint)begindeclareiintdefault1;label:repeatinsertintouser(uid,username,password)values(i,concat('user-',i),'123456');seti=i+1;untili>insertCountendrepeatlabel;select'循环结束';end$$delimiter;callproc18_repeat(100);

        这个相对于是,无论如何都会执行一次的循环,然后是在内部进行判断,如果满足了就直接跳出

        loop循环
        loop循环体;if条件表达式thenleave[标签];endif;endloop;
        ---------存储过程-循环控制-looptruncatetableuser;delimiter$$createprocedureproc19_loop(ininsertCountint)begindeclareiintdefault1;label:loopinsertintouser(uid,username,password)values(i,concat('user-',i),'123456');seti=i+1;ifi>5thenleavelabel;endif;endlooplabel;select'循环结束';end$$delimiter;callproc19_loop(10);

        这个和repeat不同的是,需要执行之后,利用leave 跳出循环,无论是使用哪种都可以达到我们需要的效果,但是在业务中的应用场景,while还是相对比较的多。

    MySQL流程控制之while、repeat、loop循环实例分析.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: mysqlwhilerepeat