我有一个包含3个表(日志数据)的MySQL数据库。每张表都有相同的结构。
现在我想编写一个每6个月运行一次的事件,并导出csv文件中的所有行,这些行超过半年,并在第二行中删除它们。 filname应包括导出的时间戳。
一开始我尝试导出一个带有静态名称的表 - 运行良好(这里有较小的时间间隔进行测试):
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;
感谢您的帮助!
答案 0 :(得分:0)
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 ;