MySQL - Table To CSV Procedure

This simple stored procedure can be used to export a table to a csv file. This procedure does not include csv headers.
  1. DROP PROCEDURE IF EXISTS table_to_csv;   
  2.   
  3. DELIMITER $   
  4.   
  5. CREATE PROCEDURE table_to_csv( IN table_name CHAR(40), IN path VARCHAR(100) )   
  6.     BEGIN   
  7.            
  8.         SET @TableName = table_name;   
  9.         SET @Path = path;   
  10.         SET @Sql = CONCAT( "SELECT * FROM ", @TableName ,  " INTO OUTFILE '", @Path, @TableName,  ".csv' FIELDS ENCLOSED BY '\"' TERMINATED BY ',' );   
  11.            
  12.         PREPARE stm1 FROM @Sql;   
  13.         EXECUTE stm1;   
  14.   
  15.     END ;   
  16. $   
  17.   
  18. DELIMITER ;   
  19.   
  20. CALL table_to_csv('table_name', 'file_path/');  

No comments:

Post a Comment