Mysql实现for循环遍历

时间:2025-03-19 17:25:16

Mysql实现for循环遍历

问题
告警表需要新增一个字段(入库时间),并把该字段作为分表的条件,该字段不能为空

需求:

新增入库时间作为查询、分表、统计的时间字段,对于历史数据,新增字段后需补充入库时间,所以把采集时间(rtime)作为入库时间(insert_time)

具体操作

num = 1
ids =(sourceSql: select id from table)
for id in ids{
targetSql: update table2 set age = num where key_id = id;
};
num ++;
这是大概逻辑,主要是通过一段sql查出数据源,然后再遍历查出来的集合做一些其他sql操作,
中间还需要一些自增的变量。

通过mysql的存储过程实现,代码如下

delimiter //  # 定义//为一句sql的结束标志,取消;的所代表的意义
drop procedure if exists test;  # 如果存在名字为test的procedure则删除
create procedure test()  # 创建(创建函数使用的关键字为function 函数名())
begin
    declare ortime datetime;  # 声明变量
    declare temp_id varchar(64);
    declare flag int default 0;
    # 这是重点,定义一个游标来记录sql查询的结果(此处的知识点还有SQL的模糊查询,见补充)
    declare s_list cursor for select id, rtime from alarm_device_confirm_2023_6; 
    # 为下面while循环建立一个退出标志,当游标遍历完后将flag的值设置为1
    declare continue handler for not found set flag=1;
    open s_list;  # 打开游标
    # 将游标中的值赋给定义好的变量,实现for循环的要点
        fetch s_list into temp_id, ortime;
        while flag <> 1 do
            # sql提供了字符串的切分,有left、right、substring、substring_index
            # 在T-SQL中,局部变量必须以@作为前缀,声明方式set,select还有点差别
            set @temp_s = ortime;
            # 根据id的唯一性,利用当前查询到的记录中的字段值来实现更新
            update alarm_device_confirm_2023_6 set insert_time=@temp_s where id=temp_id;
            # 游标往后移(此处的游标是不是让你想起了C里面的指针)
            fetch s_list into temp_id, ortime;
        end while;
        #select * from temp_table;
    close s_list;  # 关闭游标
end
//
delimiter ;  # 重新定义;为一句sql的结束标志,取消//的所代表的意义
call test(); # 调用

MySQL实现for循环逐个遍历