MySQL 名称中带有时间戳的事件 .csv 输出文件

MySQL event .csv outputfile with timestamp in name

我有一个 MySQL 数据库,其中包含 3 tables(日志数据)。每个 table 都有相同的结构。

现在我想编写一个每 6 个月运行一次的事件,并导出 csv 文件中超过半年的所有行,并在第二个中删除它们。文件名应包含导出时间戳。

一开始我尝试导出一个带有静态名称的 table - 效果很好(这里使用较小的时间间隔进行测试):

CREATE EVENT exportLog
ON SCHEDULE
EVERY 1 MINUTE
DO
SELECT *
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/exporttest.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\'
LINES TERMINATED BY '\n'
FROM mytable WHERE timestamp < (NOW() - INTERVAL 5 DAY)

现在我尝试使用包含导出时间戳的动态文件名来处理这个问题。因此,旧文件也永远不会被覆盖。但这不起作用。有人可以帮忙吗?

CREATE EVENT exportLog
ON SCHEDULE
EVERY 1 MINUTE
DO
BEGIN
SET @sql_stmt := concat("SELECT * FROM logtable INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/export_", DATE_FORMAT(now(),'%Y-%m-%d %H%i%s'),".csv'");
PREPARE extrct FROM @sql_stmt;
EXECUTE extrct;
DEALLOCATE PREPARE extrct;
END $$
DELIMITER;

感谢帮助!

DELIMITER $$
drop event if exists exportLog  $$
CREATE EVENT exportLog
ON SCHEDULE
EVERY 1 MINUTE
DO
BEGIN
declare cnt tinyint(1) default 1;
    table_loop: LOOP
        SET @sql_stmt := concat("SELECT *  INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/export_", elt(cnt, 'logtable', 'logtable1', 'logtable2'), DATE_FORMAT(now(),'%Y-%m-%d %H%i%s'),".csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\' LINES TERMINATED BY '\n' FROM ", elt(cnt, 'logtable', 'logtable1', 'logtable2'));
        PREPARE extrct FROM @sql_stmt;
        EXECUTE extrct;
        DEALLOCATE PREPARE extrct;
        SET cnt = cnt + 1;

        IF cnt < 4 THEN
          ITERATE table_loop;
        END IF;
        LEAVE table_loop;
    END LOOP table_loop;

END $$
DELIMITER ;