how to export table into flat file with different name in mysql?

折月煮酒 提交于 2019-12-13 04:03:46

问题


I am exporting a table using -

SELECT * INTO OUTFILE 'd:\\result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY  '\n'
FROM result;

Now I want to run this script daily by putting it in procedure. And I want use file name "result" with date or some other dynamic number which i can increase daily. Otherwise it will give me error for the duplicate file name.

I should be like -

declare var_result varchar(100);
set var_result = 'result01012014';
SELECT * INTO OUTFILE var_result
................................

Is it possible?


回答1:


Instead of creating Stored Procedure You can create a shell or php script for the same

Example of a shell script that I usually use

#!/bin/bash

location="/home/abdul/Desktop"
user="root"
pass="root"
table="City"
database="world_innodb"

mysql -u$user -p$pass --column-names -e "SELECT * FROM $database.$table;" | sed 's/\t/"|"/g;s/^/"/;s/$/"/;s/\n//g' > $location/$table-$(date +"%Y-%m-%d").csv

This will create file name like City-2014-02-20.csv

Stored procedure to do the same

DROP PROCEDURE IF EXISTS ExportToCSV;

DELIMITER $$

CREATE PROCEDURE `ExportToCSV`()

    BEGIN
    SET @cur_date =  CURRENT_DATE();
    SET @path = "/tmp/";
    SET @table_name =  "City";

    SET @VarSQL = CONCAT('SELECT * INTO OUTFILE  \'' ,@path,@table_name,'-',@cur_date,'.csv\' FIELDS TERMINATED BY ''\,','\' OPTIONALLY ENCLOSED BY \'','"' ,'\' LINES TERMINATED BY \'','\\n','\' FROM ',@table_name,';' );

    PREPARE stmt FROM @VarSQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    END$$

DELIMITER ;


来源:https://stackoverflow.com/questions/21908015/how-to-export-table-into-flat-file-with-different-name-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!