mysql之流程控制

本文深入解析了SQL中的分支和循环控制结构,包括if、case、while、loop及repeat语句的应用实例,如求两数最大值和数值求和,为SQL编程提供实用指南。

目录

  • 分支结构
  • 循环结构

 

分支结构:

  1.if condition then [statement] elseif condition then [statement] else [statement]  end if

   实例:求两个数中的最大值,如果两个数据相等,则返回0,不相等,则返回最大值  

delimiter //  -- 把默认的结束符;替换成//
create function test_if(a int,b int) returns int 
    BEGIN    
    DECLARE max int DEFAULT 0;
  -- 下面为分支结构
if a > b then set max = a; ELSEIF a<b then set max = b; ELSE set max = 0; end if; return max; end; // -- 查询 select test_if(1,2)

  2.case when condition then [statement] when condition then [staement] else [statement] end case

   实例:求两个数中的最大值,如果两个数据相等,则返回0,不相等,则返回最大值

delimiter //  -- 把默认的结束符;替换成
create function test_when(a int ,b int) -- 函数结构
    RETURNS int -- 返回值类型
BEGIN    -- 开始标签
DECLARE max int default 0; -- 定义内部变量表示最大值,默认为0
-- 下面为分支结构
CASE
WHEN a > b then 
SET max = a;
WHEN a < b then 
SET max = b;
ELSE 
SET max = 0;
END CASE;
RETURN max;
END;
//
-- 查询
select test_when(1,3)

循环结构:

  循环控制语句包括 while condtion do [statement]  、loop 、repeat  [statemnet] until condtion,其中while、loop满足条件开始循环,至少循环0次;而repeat满足条件退出循环,至少循环1次。

  1. while condtion do [statement] 

  实例:求和

delimiter //  -- 把默认的结束符;替换成
-- 求数值a以内的数据之和
create function test_while(a int) -- 函数结构 
returns int -- 返回值类型
begin 
    DECLARE sum int default 0; --
    DECLARE count int default 1;-- 循环次数变量
    -- 下面是循环控制语句
    la:while count <= a do 
        set sum = sum + count;
        set count = count + 1;
    end while la;
return sum;
end;
//

  2.loop 

  实例:求和

delimiter //  -- 把默认的结束符;替换成
create function demo_loop(a int) returns int
    BEGIN
    DECLARE s int DEFAULT 0;
    DECLARE i int DEFAULT 1;
    la:loop
    IF i>a then 
    LEAVE la;
    end if;
    set s = s+i;
    set i=i+1;
    end loop la;
    return s;
    end;
//
--查询
select demo_loop(1)

  3.repeat [statement] until condtion

  实例:求和

delimiter // -- 把默认的结束符;替换成//
create function demo_repeat(a int) returns int 
    begin 
    DECLARE    s int default 0;
    DECLARE i int DEFAULT 1;
    la:REPEAT
    set s = s+i;
    set i=i+1;
    UNTIL i>a
    end REPEAT la;
    return s;
    end; 
//
--查询
select demo_repeat(10)

 

转载于:https://www.cnblogs.com/wqk66/p/10858590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值