[MySQL光速入门]021 聊聊游标

游标

有点像迭代器, 一次向前推动一步, 因此若是想所有读取内容, 须要使用循环, 同时须要监听结束, 以便跳出循环sql

那何时回使用游标呢?

须要一条一条修改数据的时候...oop

drop table if exists teacher;
CREATE TABLE `teacher` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `salary` int(11) NOT NULL,
  `sex` tinyint(1) NOT NULL COMMENT '1 for male, 2 for female',
  `name` char(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `teacher`(`id`, `salary`, `sex`, `name`) VALUES (1, 4500, 1, '教师1');
INSERT INTO `teacher`(`id`, `salary`, `sex`, `name`) VALUES (2, 5500, 2, '教师2');
INSERT INTO `teacher`(`id`, `salary`, `sex`, `name`) VALUES (3, 6500, 2, '教师3');
INSERT INTO `teacher`(`id`, `salary`, `sex`, `name`) VALUES (4, 7500, 1, '教师4');
INSERT INTO `teacher`(`id`, `salary`, `sex`, `name`) VALUES (5, 8500, 2, '教师5');
复制代码

image.png

假若有一张教师表, 工资有高有低, 为了平均收入, 拉低贫富差距, 校长决定, 工资大于等于5000的老师, 工资减一千, 工资低于5000的老师, 每人工资加一千post

应该怎么作呢? 像这样?fetch

update teacher set salary = salary - 1000 where salary >= 5000;
update teacher set salary = salary + 1000 where salary < 5000;
复制代码

恐怕不行, 若是一个老师原来的工资是5500, 那么第一句以后, 他的工资会变成4500; 再执行第二句的时候, 他的工资又变回了5500...ui

因此不能所有update, 须要一条一条的修改, 这就须要游标了...spa

drop PROCEDURE if exists change_salary;
create PROCEDURE change_salary() begin 
    declare tid int default 0;
    declare tsalary int default 0;
    declare done int default 0;
    declare cur cursor for select id,salary from teacher;
    declare continue handler for not found set done = 1;
    open cur;
        myloop:loop
            fetch cur into tid,tsalary;
            if tsalary >= 5000 then
                update teacher set salary = tsalary - 1000 where id  = tid;
            else
                update teacher set salary = tsalary + 1000 where id  = tid;
            end if;
            if done then leave myloop;
            end if;
        end loop;
    close cur;
end;
call change_salary();
复制代码

中文版3d

drop PROCEDURE if exists 修改工资;
create PROCEDURE 修改工资() begin 
    declare 教师id int default 0;
    declare 教师工资 int default 0;
    declare 游标是否结束 int default 0;
    declare 游标 cursor for select id,salary from 教师表;
    declare continue handler for not found set 游标是否结束 = 1;
    open 游标;
        自定义循环名称:loop
            fetch 游标 into 教师id,教师工资;
            if 教师工资 >= 5000 then
                update 教师表 set salary = 教师工资 - 1000 where id  = 教师id;
            else
                update 教师表 set salary = 教师工资 + 1000 where id  = 教师id;
            end if;
            if 游标是否结束 then leave 自定义循环名称;
            end if;
        end loop;
    close 游标;
end;
call 修改工资();
复制代码

比较一下二者的结果差别code

image.png

image.png

image.png

最后这个结果, 才是咱们想要的cdn

快速跳转

相关文章
相关标签/搜索