存储过程循环遍历在MySQL中以100000批量删除数据的表列表

时间:2017-11-02 14:04:32

标签: mysql

我有2个模式具有完全相同的表schema_oltpschema_olap。我想从schema_oltp中的选定表中仅删除schema_olap中已存在的数据。我要删除的表列在名为archived_to_delete的表中。对于archived_to_delete中列出的每个表,我需要批量删除10万个数据。这是我到目前为止所拥有的。它只删除每张表中的10万并停止。我希望它继续,直到schema_oltp中的schema_olap中也没有数据:

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `schema_oltp`.`schemaDeletes`(IN       from_schema VARCHAR(100), IN to_schema VARCHAR(100))
BEGIN   


DECLARE v_tname varchar(100);
DECLARE v_pkey varchar(455);
DECLARE v_upfield varchar(455);
DECLARE done INT DEFAULT 0;
DECLARE v_limit INT DEFAULT 100000;
DECLARE v_deleted INT;


DECLARE table_cursor CURSOR FOR SELECT a.table_name, a.column_name 
FROM INFORMATION_SCHEMA.COLUMNS a
    INNER JOIN archived_to_delete b
    ON a.table_name = b.table_name
WHERE TABLE_SCHEMA = 'schema_oltp'
    AND COLUMN_KEY='PRI'
ORDER BY b.archived_to_delete_id;




DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;


OPEN table_cursor;

REPEAT

FETCH table_cursor INTO v_tname, v_pkey;

IF NOT done THEN



    SET v_deleted=0;
      SET @sql = CONCAT('DELETE FROM ',from_schema,'.', v_tname, '  WHERE ',v_pkey,' IN (SELECT ', v_pkey, ' FROM ',to_schema,'.', v_tname, ')  limit ',v_limit,';');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET v_deleted=v_deleted+1;
IF v_deleted = v_limit THEN
commit;
SET v_deleted=0;
END IF;


    SELECT CONCAT('Deleting...',v_tname);

 END IF;

 UNTIL done END REPEAT;
 CLOSE table_cursor;



    END$$

DELIMITER ;

0 个答案:

没有答案