Search code examples
mysqlcsvinto-outfile

mysq - Use variable (date) when SELECT * INTO OUTFILE (on file name)


Good afternoon,

I'm using INTO OUTFILE to create a CSV file with the information of a SELECT. I need to use variables to personalize the name of the CSV.

For example, I want to add the date NOW().

This is the idea (but its not working):

SET @outpath = "out/";
SET @outfile = (SELECT NOW());
SET @outextension = "_EMAIL_WithoutEmail.csv";
SET @outfull = CONCAT(@outpath,@outfile,@outextension);
SELECT *
    FROM `vn_db_tmp`
    INTO OUTFILE @outfull
    FIELDS TERMINATED BY ';'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';

Anyonw knows if it's possible? Thanks


Solution

  • One option is to use 13.5 Prepared SQL Statement Syntax.

    Example:

    ...
    
    SET @`outfull` := CONCAT('out/', NOW(), '_EMAIL_WithoutEmail.csv');    
    SET @`qry` := CONCAT('SELECT * 
                            INTO OUTFILE \'', @`outfull`, '\' 
                            FIELDS TERMINATED BY \';\' 
                            ENCLOSED BY \'"\' 
                            LINES TERMINATED BY \'\n\' 
                          FROM `vn_db_tmp`');    
    PREPARE `stmt` FROM @`qry`;
    SET @`qry` := NULL;
    EXECUTE `stmt`;
    DEALLOCATE PREPARE `stmt`;
    ...