直接上代碼sql
-- 刪除存儲過程 DROP PROCEDURE IF EXISTS `renew_message_queue`; -- 添加; 的轉義 DELIMITER ;; CREATE PROCEDURE `renew_message_queue`() BEGIN -- 舊錶備份的後綴 DECLARE old_table_suffix VARCHAR(8) DEFAULT DATE_FORMAT(NOW(), '%Y%m%d'); -- 事務標記 DECLARE t_error INTEGER DEFAULT 0; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET @t_error=1; START TRANSACTION; -- 建立表 CREATE TABLE `ecm_message_queue_new` LIKE `ecm_message_queue`; -- 備份舊錶 SET @back_table_sql = CONCAT('ALTER TABLE ecm_message_queue RENAME TO ecm_message_queue_bak_', old_table_suffix); -- 執行動態生成的sql語句 PREPARE temp FROM @back_table_sql; EXECUTE temp; -- 重命名新表 ALTER TABLE ecm_message_queue_new RENAME TO ecm_message_queue; -- 將未處理的數據遷移到新表 SET @move_data_sql = CONCAT('INSERT INTO `ecm_message_queue` SELECT * FROM ecm_message_queue_bak_', old_table_suffix, ' WHERE send_status = 0'); -- 執行動態生成的sql語句 PREPARE temp FROM @move_data_sql; EXECUTE temp; IF t_error = 1 THEN ROLLBACK; ELSE COMMIT; END IF; -- 返回標識位的結果集,可不執行 -- select t_error; END; ;; DELIMITER ; CALL `renew_message_queue`();
Have fun with MySQL!spa