参考链接: https://www.cnblogs.com/progor/p/8875100.html
class与class2原来是单向一对一关系,要改为一对多的关系,但要保留原来的数据 ,如图
class表
class2表
也就是想根据已知去填充class_id部分
游标
- 1.定义游标:declare 游标名 cursor for select语句;
- 2.打开游标:open 游标名;
- 获取结果:fetch 游标名 into 变量名[,变量名];
- 关闭游标:close 游标名;
DROP PROCEDURE IF EXISTS p;
create procedure p()
begin
declare classId varchar(255);
declare class2Id varchar(255);
declare flag int default 0;
-- 声明游标
declare mc cursor for select id,class2_id from class where class2_id is not null;
declare continue handler for not found set flag = 1;
-- 打开游标
open mc;
-- 获取结果
l2:loop
fetch mc into classId,class2Id;
if flag=1 then -- 当无法fetch会触发handler continue
leave l2;
end if;
-- 这里是为了显示获取结果
update class2 set class_id = classId where id = class2Id;
-- 关闭游标
end loop;
close mc;
end;
call p();