使用当日mysql创建CSV文件

时间:2018-11-09 16:14:25

标签: mysql csv into-outfile

如何将具有日期和时间的数据从mysql导出到文件csv。我尝试了此代码,但出现错误

SELECT *
FROM order
INTO OUTFILE '/tmp/',NOW(),'_orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

这是我的错误

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"' ,NOW(), '"'_orders.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TER' at line 3

这是我的活动,效果很好,但是我想在本月的每个月末使用不同的简历

CREATE DEFINER = `admin`@`localhost` EVENT `Order` 
ON SCHEDULE EVERY1 MONTH STARTS '2018-12-01 00:00:00' 
ON COMPLETION NOT PRESERVE ENABLE 
COMMENT 'Order save' 
DO SELECT *
FROM Order
INTO OUTFILE '/tmp/_orders.csv'

在此查询中获取带有日期的名称,但我无法在事件中添加该名称

SET @`outfull` := CONCAT('/tmp/', NOW(), 'orders.csv');
SET @`qry` := CONCAT('SELECT * 
                        INTO OUTFILE \'', @`outfull`, '\' 
                        FIELDS TERMINATED BY \';\' 
                        ENCLOSED BY \'"\' 
                        LINES TERMINATED BY \'\n\' 
                      FROM `order`');

PREPARE `stmt` FROM @`qry`;
SET @`qry` := NULL;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;

1 个答案:

答案 0 :(得分:1)

尝试准备好的语句:

set @sql = concat('SELECT *
FROM tradooITLangues 
INTO OUTFILE ', concat('\'', '/tmp/', NOW(), '_orders.csv', '\''),
' FIELDS TERMINATED BY \',\'
ENCLOSED BY \'"\'
LINES TERMINATED BY \'#\n\';');

PREPARE stmt1 FROM @sql;
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1; 

在一个事件中(我的MySQL接受了语法):

delimiter $$
CREATE DEFINER = `admin`@`localhost` EVENT `Order` 
ON SCHEDULE EVERY 1 MONTH STARTS '2018-12-01 00:00:00' 
ON COMPLETION NOT PRESERVE ENABLE 
COMMENT 'Order save' 
DO
BEGIN

    SET @`outfull` := CONCAT('/tmp/', NOW(), 'orders.csv');
    SET @`qry` := CONCAT('SELECT * 
                            INTO OUTFILE \'', @`outfull`, '\' 
                            FIELDS TERMINATED BY \';\' 
                            ENCLOSED BY \'"\' 
                            LINES TERMINATED BY \'\n\' 
                          FROM `order`');

    PREPARE `stmt` FROM @`qry`;
    SET @`qry` := NULL;
    EXECUTE `stmt`;
    DEALLOCATE PREPARE `stmt`;

END;
$$