DELIMITER $$

CREATE PROCEDURE DropEntityChangeTables()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE table_name VARCHAR(255);
    DECLARE drop_stmt VARCHAR(512);

    DECLARE cur CURSOR FOR
        SELECT CONCAT('DROP TABLE IF EXISTS entity_changes_', table_name)
        FROM entity_changes_metadata
        WHERE is_auditable = TRUE;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN cur;

    read_loop: LOOP
        FETCH cur INTO drop_stmt;
        IF done THEN
            LEAVE read_loop;
        END IF;

        SET @s = drop_stmt;
        PREPARE stmt FROM @s;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP;

    CLOSE cur;
END$$

DELIMITER ;


CALL DropEntityChangeTables();