mysql - 当 SELECT * INTO OUTFILE(在文件名上)时使用变量(日期)

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

下午好,

我正在使用 INTO OUTFILE 创建一个包含 SELECT 信息的 CSV 文件。 我需要使用变量来个性化 CSV 的名称。

比如我想添加日期NOW()。

这是想法(但行不通):

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';

任何人都知道这是否可能? 谢谢

唯一的方法是使用 PREPARE STATEMENT

// You can set your VARS or use it direcly in the CONCAT
SET @outpath = "out/";
SET @outfile = (SELECT NOW());
SET @outextension = "_EMAIL_WithoutEmail.csv";

// GENERATE your QUERY with CONCAT into @SQL
SELECT CONCAT("SELECT * FROM `vn_db_tmp` INTO OUTFILE ",@outpath,@outfile,@outextension,'....') INTO @SQL;
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

一种选择是使用 13.5 Prepared SQL Statement Syntax

示例:

...

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`;
...

就放在那里吧。为避免输出文件出现问题,您必须使用 'path to file'。使用反斜杠+'作为'特殊符号。

SET @outfull = CONCAT('\'/path/to/file/', date_format (NOW(),'%Y-%m-%d_%H:%i:%s'), '_app.log\'');    
SET @SQL = CONCAT("SELECT * FROM some_table INTO OUTFILE ",@outfull);    
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;