Search code examples
mysqlphpmyadminexport-to-csvinformation-schema

How to export all tables from a database ordered by a common column?


I want to export each table from a database to a separated csv file ordered by a commom column to all tables. I'm using MySql, phpMyAdmin and Windows 10

I'm a newbie in MySql and searching on Stackoverflow I could get to this code that exports one table to a csv file, exactly as I want:

SELECT * INTO OUTFILE 'c://path/name_of_table.csv'
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '' 
LINES TERMINATED BY '\n' 
FROM `name_of_table` ORDER BY name_of_column;

Could I iterate over all tables from a specific database using the table name as a variable in my above query?

Something like:

FOREACH my_table IN my_database

    SELECT * INTO OUTFILE 'c://path/' .my_table.table_name. '.csv'
    FIELDS TERMINATED BY ',' 
    OPTIONALLY ENCLOSED BY '' 
    LINES TERMINATED BY '\n' 
    FROM `my_table.table_name` ORDER BY name_of_column;

END FOREACH;

Any other approach is also wellcome

Thanks!


Solution

  • You were halfway there.

    One solution would be to use a stored procedure with a cursor to get the table names and some dynamic SQL to make the SELECT INTO OUTFILE statement.

    Something like this should work.

    DELIMITER //
    
    DROP PROCEDURE IF EXISTS db_export_csv //
    CREATE PROCEDURE db_export_csv(_path VARCHAR(255), _sname VARCHAR(64))
    BEGIN
      DECLARE tname VARCHAR(64);
      DECLARE done BOOLEAN DEFAULT FALSE;
    
      DECLARE cur CURSOR FOR 
        SELECT `table_name`
        FROM `information_schema`.`tables`
        WHERE `table_schema` = _sname
        AND `table_type` = 'BASE TABLE';
    
      DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;
      OPEN cur;
    
      myloop: LOOP
        FETCH cur INTO tname;
        IF done THEN 
          LEAVE myloop; 
        END IF;
    
        SET @sql = CONCAT("SELECT * INTO OUTFILE \'" , _path , '' , tname , '_' , CURRENT_DATE , ".csv\' ",
          "FIELDS TERMINATED BY ',' ", 
          "OPTIONALLY ENCLOSED BY '''' ",
          "LINES TERMINATED BY '\n' ", 
          "FROM `" , _sname , "`.`" , tname , "` ORDER BY `yrcolname` ASC");
    
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    
      END LOOP; 
    
    END //
    
    DELIMITER ;
    
    CALL db_export_csv('/var/lib/mysql-files/', 'test');
    

    Obviously, I've tested it on Linux, so you would put your own writable path in (allowing for the setting of @@global.secure_file_priv) and you should change yrcolname to an appropriate value.