Skip to content

Instantly share code, notes, and snippets.

@ancho85
Created July 18, 2016 13:52
Show Gist options
  • Save ancho85/21726ed1ad53f14c7ec4cfd80e27b53d to your computer and use it in GitHub Desktop.
Save ancho85/21726ed1ad53f14c7ec4cfd80e27b53d to your computer and use it in GitHub Desktop.
MySQL empty table dropper
DELIMITER $$
DROP PROCEDURE IF EXISTS `anchoDropEmptyTables` $$
CREATE PROCEDURE `anchoDropEmptyTables`()
BEGIN
-- contar las tablas
DECLARE table_list TEXT;
DECLARE done INT DEFAULT 0;
DECLARE TNAME CHAR(255);
DECLARE table_names CURSOR for
SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN table_names;
DROP TABLE IF EXISTS TCOUNTS;
CREATE TEMPORARY TABLE TCOUNTS
(
TABLE_NAME CHAR(255),
RECORD_COUNT INT
) ENGINE = MEMORY;
WHILE done = 0 DO
FETCH NEXT FROM table_names INTO TNAME;
IF done = 0 THEN
SET @SQL_TXT = CONCAT("INSERT INTO TCOUNTS(SELECT '" , TNAME , "' AS TABLE_NAME, COUNT(*) AS RECORD_COUNT FROM `", TNAME, "`)");
PREPARE stmt_name FROM @SQL_TXT;
EXECUTE stmt_name;
DEALLOCATE PREPARE stmt_name;
END IF;
END WHILE;
CLOSE table_names;
SELECT * FROM TCOUNTS;
-- filtrar las que no tienen datos y borrarlas
SET group_concat_max_len=4294967295;
SELECT
GROUP_CONCAT('`',`TABLE_NAME`,'`')
INTO
table_list
FROM TCOUNTS
WHERE RECORD_COUNT = 0;
SET @drop_tables = CONCAT("DROP TABLE ", table_list,';');
select @drop_tables;
IF table_list IS NOT NULL THEN
SET @drop_tables = CONCAT("DROP TABLE ", table_list,';');
select @drop_tables;
PREPARE stmt FROM @drop_tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
DELIMITER ;
CALL anchoDropEmptyTables();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment