MySQL游标(Cursor)

  1. 1. 语法
  2. 2. 案例

​ 在 MySQL 中,存储过程或函数中的查询有时会返回多条记录,而使用简单的 SELECT 语句,没有办法得到第一行、下一行或前十行的数据,这时可以使用游标来逐条读取查询结果集中的记录。

一般通过游标定位到结果集的某一行进行数据修改。

结果集是符合 SQL 语句的所有记录的集合。个人理解游标就是一个标识,用来标识数据取到了什么地方,如果你了解编程语言,可以把他理解成数组中的下标。

语法

1
2
3
4
5
6
7
8
9
10
11
-- 声明游标
declare 游标名 cursor for select语句;

-- 打开游标
open 游标名;

-- 获取游标数据,获取到最末尾会报02000错误
fetch 游标名 INTO 变量 [, 变量 ];

-- 关闭游标
close 游标名;

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
create procedure myCursor()

BEGIN

declare myDeptno int;
declare myMinSal decimal(10,3);
declare myMaxSal decimal(10,3);

declare xx cursor for select deptno,min(sal) as minSal,max(sal) as maxSal from emp group by deptno;

drop table if EXISTS summary;

create table summary(
deptno int primary key,
min_sal decimal(10,3),
max_sal decimal(10,3)
);

open xx;

WHILE true DO
fetch xx into myDeptno,myMinSal,myMaxSal;
insert into summary values(myDeptno,myMinSal,myMaxSal);
END WHILE;

close xx;
END;

call myCursor();