mysql代码执行结构实例分析【顺序、分支、循环结构】

吾爱主题 阅读:202 2024-04-05 16:21:10 评论:0

本文实例讲述了mysql代码执行结构。分享给大家供大家参考,具体如下:

本文内容:

 首发日期:2018-04-18


什么是代码执行结构:

  • 这里所说的代码执行结构就是多条sql语句的执行顺序。
  • 代码执行结构主要用于触发器、存储过程和函数等存储多条sql语句中。

顺序结构:

  • 顺序结构就是从上到下依次执行sql语句
  • 一般默认情况下都是顺序结构

分支结构:

  • 分支结构的执行是依据一定的条件选择执行路径,它会依据我们给定的条件来选择执行那些sql语句
  • mysql中分支结构只有if-else:
    • 语法: ?
      1 2 3 4 5 6 7 if 条件 then   sql语句 [elseif 条件 then   sql语句] [ else   sql语句] end if;
    • 示例: ?
      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -- create table pass(id int primary key auto_increment, name varchar (15),score int ); create table unpass(id int primary key auto_increment, name varchar (15),score int );   -- 使用存储过程来 create procedure myif( in name varchar (15), in score int ) begin   if score >=60 then    insert into pass( name ,score) values ( name ,score);   else    insert into unpass( name ,score) values ( name ,score);   end if; end ; -- 调用,并查看结果 call myif( "lilei" ,61); call myif( "hanmeimei" ,95); select * from pass; select * from unpass; call myif( "tuhao" ,59); select * from unpass;
    • if中的条件基本可以参照select语句的while子句的条件。什么in\not in \= \!= 等都可以用。 ?
      1 2 3 4 5 6 7 8 9 10 11 create procedure myif3( in a char (1)) begin   if a in ( 'a' , 'b' ) then    select 1;   else    select 2;   end if; end ; call myif3( 'a' ); call myif3( 'b' ); call myif3( 'c' );

补充:

  • 理论上,如果做出判断不符合,然而又不想继续执行下去的时候,应该执行返回(比如c语言的return来中断函数运行),但mysql中并没有对应的中断机制,所以需要我们主动中断(中断的方法有很多种,比如执行一条符合语法但无法运行的语句)【这种场景比如有:判断一名学生是否存在,不存在就不执行任何操作,所以应该执行一条无法成功运行的语句来报错返回。】
  • 事实上,还存在一种分支结构:case when 【好像好多书都没怎么讲到,所以这里不讲述。有兴趣的可以自行百度。】

循环结构:

    • 循环结构是指在程序中需要反复执行某个功能而设置的一种程序结构。mysql中循环结构用于循环多次运行同一sql语句。
    • mysql中的循环结构有loop结构、while结构、repeat结构,这里只讲述while结构,有兴趣了解其他的可以自行百度。
    • 语法:
?
1 2 3 while 条件 do   sql语句 end while;
      • 学过其他语言的可能会了解到循环结构中有continue(提前结束此次循环)和break(跳出整个循环)
        在mysql的循环结构中,使用leave来代替break,使用iterate来代替continue,但它们的使用语法是:leave\iterate 循环名,所以如何定义循环名呢?
?
1 2 3 4 循环名:while 条件 do   sql语句;   leave\iterate 循环名; end while;
  • 示例: ?
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 -- 无意义的一个例子,仅作演示 create table whilenum(id int ); -- 自带条件的 create procedure mywhile() begin   declare num int ;   set num=10;   c1:while num>0 do     insert into whilenum values (num);     set num=num-1;    end while; end ; -- 以传入参数作为条件的 create procedure mywhile2( in num int ) begin   c1:while num>0 do     insert into whilenum values (num);     set num=num-1;    end while; end ; -- 带中断的 create procedure mywhile3( in num int ) begin   c1:while num>0 do     if num%2=0 then      set num=num-1;      iterate c1;     end if;     insert into whilenum values (num);     set num=num-1;    end while; end ;

希望本文所述对大家MySQL数据库计有所帮助。

原文链接:https://www.cnblogs.com/progor/p/8874644.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容