Mysql-存储过程-游标

BEGIN

    #1.定义变量 声明格式:DECLARE 变量名 类型 默认值;
    #DECLARE user_names VARCHAR(25) DEFAULT '刘猛';

    #2.变量赋值 set 变量名 =值;
    #set user_names='刘猛';

    #3.if函数 if(条件表达式,值1,值2);
    #if(user_names,user_names,"请输出用户名");

    #4.if结构 
    #if(表达式) 
    # then  值1;
    #ELSEIF(表达式) 
    # then 值2;
    #ELSE 值3;
    #end if;

    #DECLARE ch CHAR DEFAULT 'A';
    #DECLARE score INT DEFAULT 80;
    #IF score>90 THEN SET ch='A';
    #ELSEIF score>80 THEN SET ch='B';
    #ELSEIF score>60 THEN SET ch='C';
    #ELSE SET ch='D';
    #END IF;
    #select ch;

    #5.case 结构体
    #case(变量值或表达式)
    #when 成立1 then 值1;
    #when 成立2 then 值2;
    #ELSE  值3;
    #END CASE;

    #CASE 
    #WHEN score>90 THEN SET ch='A';
    #WHEN score>80 THEN SET ch='B';
    #WHEN score>60 THEN SET ch='C';
    #ELSE SET ch='D';
    #END CASE;   
    #select ch;

    #6.while 循环结构
    #while 结束循环条件 do
    #循环体
    #end WHILE;

    #DECLARE total INT DEFAULT 0;
    #DECLARE i INT DEFAULT 1;
    #DECLARE insertCount  INT DEFAULT 20;
    #WHILE i<=insertCount DO
    #        set total:=total+i;
    #        SET i=i+1;
    #END WHILE;
    #select total;

    #7.repeat
    #循环体
    #until 结束循环条件
    #end repeat;

    #DECLARE total int DEFAULT 0;
    #REPEAT
    #set total=total+1;
    #until total>10
    #end repeat;
    #SELECT total;

    #8.游标
    #声明游标 DECLARE  游标名称 CURSOR FOR sql语句;
    #打开游标 OPEN 游标名称;
    #遍历结果 FETCH 游标名称 INTO var_name;
    #关闭游标 CLOSE 游标名称;
    #select en.user_name  from enduser_info as en;
    
    declare user_nameS varchar(255); #获取名称
    declare fidS int(11);
    declare tels varchar(11);
    declare done INT DEFAULT FALSE;

    -- 声明游标
    declare mc cursor for select fid,user_name,tel from enduser_info LIMIT 5;
    # 指定游标循环结束时的返回值
    declare exit HANDLER for not found set done := true;
    -- 打开游标
    open mc;
    # 开始循环游标里的数据

    #read_loop:loop loop 循环
    #if done then
    #  leave read_loop;    # 跳出游标循环
    #end if;
    #有loop 就一定要有end loop
    #end loop;

    #repeat循环
    repeat
    -- 获取结果
      fetch mc into fidS,user_nameS,tels;
      select fidS,user_nameS,tels;
    # 判断游标的循环是否结束
    until done end repeat;

    -- 这里是为了显示获取结果
    #select fid,user_name,tel from enduser_info LIMIT 5;
    -- 关闭游标
    close mc;
    #9.iterate: 类似于 continue,继续,结束本次循环,继续下一次
    #leave: 类似于  break,跳出,结束当前所在的循环
END

 

posted @ 2019-07-22 14:18  MSJ521  阅读(64)  评论(0)    收藏  举报