DROP PROCEDURE IF EXISTS myPurge;
-- Will be used to signify the end of the procedure
DELIMITER ;;
-- Use a procedure
CREATE PROCEDURE myPurge()
BEGIN
-- Retrieve tables from information_schema and
-- Store them into a temporary table
DROP TABLE IF EXISTS tempTables;
CREATE TEMPORARY TABLE tempTables
SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_db';
-- Initialise variables
SET @i = 0;
SELECT COUNT(*) FROM tempTables INTO @n;
-- Loop from 0 to number of rows
WHILE @i < @n DO
-- Retrieve table from row @i
-- SELECT * FROM tempTables LIMIT @i, 1 INTO @atable; -- doesn't seem to work on MySQL v5
-- Prepare and execute a subsidiary query
SELECT CONCAT("SELECT * FROM tempTables LIMIT ", @i, ",1 INTO @atable") INTO @preLimStmt;
PREPARE limStmt FROM @preLimStmt;
EXECUTE limStmt;
-- Save statement into temporary variable
-- HERE we prepare your PURGE
SELECT CONCAT("DELETE FROM my_db.", @atable, " WHERE set_id > 2170") INTO @preStmt;
-- Prepare and execute the purge statement
PREPARE stmt FROM @preStmt;
EXECUTE stmt;
-- Increment @i
SET @i = @i + 1;
END WHILE;
END;;
-- Call the procedure
CALL myPurge();
-- cleanup
DEALLOCATE PREPARE limStmt;
DEALLOCATE PREPARE stmt;
-- Reset to default
DELIMITER ;
-- Remove the temporary table
DROP TABLE tempTables;
2条答案
按热度按时间cuxqih211#
我想,这不是一个问题,但你可以这样做
结果就是所有需要运行的查询。你可以复制并运行它。
vvppvyoh2#
我喜欢马可的答案,因为它很短,提供了一个很好的解决办法。这就是我使用过程、while循环和prepared语句所想到的。不需要复制。
它检索并存储到一个临时表中,然后遍历每个表名并执行单独的delete语句。
注意:我使用的是MySQL5.7.23版本。