ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
转载自:https://www.jb51.net/article/70677.htm **** **1. 什么是光标(游标)** 查询语句可能会有多条记录,在存储过程或函数中使用光标可以逐条获取结果集中的记录。 <br/> **2. 光标的使用步骤** ```sql 1. 声明光标 # 光标必须声明在处理程序之前,在变量和条件之后 DECLARE cursor_name CURSOR FOR select_statement; 2. 打开光标 OPEN cursor_name; 3. 使用光标 FETCH cursor_name INTO var_name[, var_name, ...]; 4. 关闭光标 # 每个光标不再需要时应该关闭,以便释放光标所占的资源 # 对于声明过的光标不需要再次声明,直接用open打开即可使用 CLOSE cursor_name; - cursor_name:自定义的光标名称 - select_statement:select 查询语句 - var_name:select 语句查询出来的信息存入该变量中,该变量必须在声明光标之前定义好 ``` **3. 演示** 将表`account`的数据复制一份到表`account_copy`中。 ```sql # 1. 数据准备 drop table if exists account; create table account ( id int primary key auto_increment not null, username varchar(255) not null, password varchar(255) not null ); insert into account values(1, '张三', 'zhangsan'); insert into account values(2, '李四', 'lisi'); drop table if exists account_copy; create table account_copy ( id int primary key auto_increment not null, uname varchar(255) not null, pass varchar(255) not null ); # 2. 在存储过程中使用光标 delimiter $ create procedure proce_cur() begin declare id_ int(11); declare count_ int(11); declare uname_ varchar(255); declare pass_ varchar(255); -- 声明光标 declare cursor_account cursor for select * from account; declare continue handler for sqlstate '02000' set @info = 'ERROR'; select count(id) into count_ from account; -- 打开光标 open cursor_account; repeat -- 使用光标,将光标中的值赋值给下面三个变量 fetch cursor_account into id_, uname_, pass_; insert into account_copy values(id_, uname_, pass_); set count_ = count_ - 1; until count_ <= 0 end repeat; -- 关闭光标 close cursor_account; end $ # 3. 调用存储过程 call proce_cur() $ # 4. 查看结果 mysql> select * from account_copy $ +----+--------+----------+ | id | uname | pass | +----+--------+----------+ | 1 | 张三 | zhangsan | | 2 | 李四 | lisi | +----+--------+----------+ ```