MySQL存储过程:将machine_status_active数据批量插入machine_status_tiny表
{"title":"MySQL存储过程:将machine_status_active数据批量插入machine_status_tiny表","description":"使用MySQL存储过程,根据指定天数,将machine_status_active表中创建时间范围内的历史数据批量插入machine_status_tiny表,每次插入10万条数据。","keywords":"MySQL, 存储过程, 批量插入, machine_status_active, machine_status_tiny, 数据迁移, 历史数据, 创建时间","content":""DELIMITER //\n\nCREATE PROCEDURE insert_data_to_tiny(IN days INT)\nBEGIN\n\tDECLARE total_count INT;\n\tDECLARE current_count INT;\n\tDECLARE start_date DATE;\n\tDECLARE end_date DATE;\n\n\tSET total_count = (SELECT COUNT(*) FROM machine_status_active WHERE created_at >= CURDATE() - INTERVAL days DAY);\n\tSET current_count = 0;\n\tSET start_date = CURDATE() - INTERVAL days DAY;\n\tSET end_date = CURDATE();\n\n\tWHILE current_count < total_count DO\n\t INSERT INTO machine_status_tiny\n\t SELECT *\n\t FROM machine_status_active\n\t WHERE created_at >= start_date AND created_at < end_date\n\t LIMIT 100000;\n\n\t SET current_count = current_count + ROW_COUNT();\n\tEND WHILE;\nEND //\n\nDELIMITER ;\n\n使用方法:\n1. 将上述存储过程代码复制到MySQL客户端中,执行代码创建存储过程。\n2. 调用存储过程,并传入天数参数,例如:CALL insert_data_to_tiny(7);,这将提取过去7天内的数据并插入到machine_status_tiny表中,每次插入10W条数据,直到所有符合条件的数据都被插入为止。\n\n请注意,以上存储过程仅作为示例提供,具体根据实际需求进行调整。"}
原文地址: https://www.cveoy.top/t/topic/qjDM 著作权归作者所有。请勿转载和采集!