美文网首页
存储过程(三)

存储过程(三)

作者: 三斤耳朵 | 来源:发表于2018-12-10 23:52 被阅读79次

    演示一个完整的使用游标的案例

    mysql> CREATE TABLE IF NOT EXISTS `store` (
        -> `id` int(11) NOT NULL AUTO_INCREMENT,
        -> `name` varchar(20) NOT NULL,
        -> `count` int(11) NOT NULL DEFAULT '1',
        -> PRIMARY KEY (`id`)
        -> );
    Query OK, 0 rows affected (0.07 sec)
    
    mysql> INSERT INTO `store` (`id`, `name`, `count`) VALUES (1, 'android', 15), 
    (2, 'iphone', 14),(3, 'iphone', 20), (4, 'android', 5),(5, 'android', 13),
    (6, 'iphone', 13);
    Query OK, 6 rows affected (0.05 sec)
    Records: 6  Duplicates: 0  Warnings: 0
    
    mysql> CREATE PROCEDURE StatisticStore()
        -> BEGIN
        --创建接收游标数据的变量
        -> declare c int;
        -> declare n varchar(20);
        --创建总数变量
        -> declare total int default 0;
        --创建结束标志变量
        -> declare done int default false;
        --创建游标
        -> declare cur cursor for select name,count from store where name = 'iphone';
        --指定游标循环结束时的返回值
        -> declare continue HANDLER for not found set done = true;
        --设置初始值
        -> set total = 0;
        --打开游标
        -> open cur;
        --开始循环游标里的数据
        -> iphone_loop:loop
        --根据游标当前指向的一条数据
        -> fetch cur into n,c;
        --判断游标的循环是否结束
        -> if done then
        -> leave iphone_loop;--跳出游标循环
        -> end if;
        --获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作,
        -> set total = total + c;
        --结束游标循环
        -> end loop;
        --关闭游标
        -> close cur;
        --输出结果
        -> select n,total;
        -> end //
    Query OK, 0 rows affected (0.04 sec)
    
    mysql> call StatisticStore();
    +--------+-------+
    | n      | total |
    +--------+-------+
    | iphone |    47 |
    +--------+-------+
    1 row in set (0.04 sec)
    
    Query OK, 0 rows affected (0.04 sec)
    

    相关文章

      网友评论

          本文标题:存储过程(三)

          本文链接:https://www.haomeiwen.com/subject/ezpjhqtx.html