SQL必知必会-笔记(十一)游标

有时需要在检索出来的行中前进或后退一行或多行,这就是游标的用处所在。

下面使用一个例子来说明游标的使用:

create procedure processorders()
begin
  declare done boolean default 0;
  declare o int;
  declare t decimal(8,2);

  -- 声明游标
  declare ordernumbers cursor for select order_num from Orders;
  -- 定义了一个CONTINUE HANDLER,这条语句定义了一个CONTINUE HANDLER,它是在条件出现时被执行的代码。这里, 它指出当SQLSTATE '02000'出现时, SET done=1 SQLSTATE'02000'是一个未找到条件, 当REPEAT由于没有更多的行供循环而不能继续时,出现这个条件。用DECLARE语句定义的局部变量必须在定义任意游标或句柄之前定义,而句柄必须在游标之后定义。
  declare continue handler for sqlstate '02000' set done=1;
  -- 创建一个表存储结果
  create table if not exists ordertotals (order_num int,total decimal(8,2));
  -- 打开游标
  open ordernumbers;
  -- 遍历所有行
  repeat
        -- FETCH用来检索当前行的order_num列 (将自动从第一行开始)到一个名为o的局部声明的变量中
        fetch ordernumbers into o;
        -- 上一节中写的存储过程
        call ordertotal(o,1,t);
        insert into ordertotals(order_num, total) VALUES (o,t);
  until done end repeat;
  close ordernumbers;
end;
call processorders();
select * from ordertotals;

猜你喜欢

转载自www.cnblogs.com/xLI4n/p/10406751.html