mysql游标用于遍历处理数据集

mysql游标用于遍历处理数据集

1 应用场景

项目版本更迭后,以前的数据库保存的是二级行业信息的行业id industry_id,现在需要保存一级行业的行业id.
这就导致,我需要遍历fgmp_chatbot中的所有行业id,然后逐个替换一级行业id.

2 操作示例

delimiter //
drop procedure if exists compatibility_old_data;   #如果存储过程compatibility_old_data存在则删除
create procedure compatibility_old_data()   #创建存储过程compatibility_old_data
begin   #开始存储过程
	declare temp_id int;  #声明变量
    declare temp_industry_id int;
    declare flag int default 0;
	declare temp_parent_industry_id int;
	
    declare s_list cursor for select id, industry_id from fgmp_chatbot ; #声明游标
    declare continue handler for not found set flag=1; #当遍历完全部游标中的数据后,把判断条件改为否

    open s_list;  #打开游标
        fetch s_list into temp_id, temp_industry_id;  #从游标中获取数据
        while flag <> 1 do   #判断是否进行循环
            select parent_id from fgmp_chatbot_industry where id = temp_industry_id into temp_parent_industry_id;  #从fgmp_chatbot_industry中取出一个父行业id放入变量temp_parent_industry_id中
				if temp_parent_industry_id =0 then #判断该行业id是否是一级行业id
                    update fgmp_chatbot set industry_id=temp_industry_id where id=temp_id;
                end if;
				if temp_parent_industry_id !=0 then  #判断该行业id是否是二级级行业id
                    update fgmp_chatbot set industry_id=temp_parent_industry_id where id=temp_id;
                end if;
            fetch s_list into temp_id, temp_industry_id; #从游标中获取数据,游标后移
        end while; #结束循环
    close s_list;  #关闭游标
end; 关闭存储过程
//
delimiter ;
call compatibility_old_data(); #调用

Guess you like

Origin blog.csdn.net/Ssucre/article/details/120886662