Home  >  Article  >  Database  >  MySQL stored procedure-->Migrate data to history table through cursor traversal and exception handling

Migrate data to history table through cursor traversal and exception handling

-->

MySQL stored procedure-->Migrate data to history table through cursor traversal and exception handling

黄舟
黄舟Original
2017-02-17 11:34:221389browse

-- Large table data migration,Every morning1 Click to 5 and click to execute, the execution interval is 10 minutes, migrate old data to the history table.

DELIMITER $$
 
USE `dbx`$$
 
DROP PROCEDURE IF EXISTS `pro_xx`$$
 
CREATE  PROCEDURE `pro_xx`()
BEGIN  
   DECLARE p_oalid INT DEFAULT 0;
   DECLARE STOP INT DEFAULT 0; 
   
   DECLARE cur_oalid CURSOR FOR
         SELECToal.id FROM oal_xxx oal WHERE oal.`ymd` <CONCAT(YEAR(DATE_ADD(NOW(),INTERVAL -1 MONTH)),&#39;-&#39;,MONTH(DATE_ADD(NOW(),INTERVAL -1 MONTH )),&#39;-&#39;,
         DAY(DATE_ADD(NOW(),INTERVAL-1 MONTH ))) LIMIT 1000;  
   DECLARE EXIT HANDLER FOR SQLSTATE &#39;02000&#39;  /**包含游标not found*/
   BEGIN
        SET STOP=1;
         INSERTINTO db_logs(log_type,table_name,action_name,log_msg,create_time)
         SELECT1, &#39;oal_xxx&#39;,&#39;pro_oal_log_move&#39;,CONCAT(&#39;primary key:&#39;,p_oalid,&#39; 游标执行正常结束!&#39;),NOW();       
   END;
       
   DECLARE EXIT HANDLER FOR SQLEXCEPTION
   BEGIN
         SETSTOP=1;
         INSERTINTO db_logs(log_type,table_name,action_name,log_msg,create_time)
         SELECT2, &#39;oal_xxx&#39;,&#39;pro_oal_log_move&#39;,CONCAT(&#39;primary key:&#39;,p_oalid,&#39; 移动执行失败&#39;),NOW();
   END; 
   
   OPEN cur_oalid;

                                                                                                                                                                                                     

## -- This is to determine whether the cursor has reached the end

FETCH cur_oalid INTO p_oalid;

--

Perform data migration

 WHILE STOP <> 1 DO 
         -- select p_id;
         START TRANSACTION;
                                                                                                                                                                                                  

   REPLACE INTO oal_xxx_history SELECT oal.*FROM oal_xxx oal WHERE oal.id=p_oalid ;
             DELETE FROM oal_xxx WHERE id=p_oalid;
                          
             -- INSERT INTO t (tid) VALUES (p_tid);
         COMMIT;

The above is the content of the MySQL stored procedure --> migrating data to the history table through cursor traversal and exception handling. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn