2017-04-24 69 views
0

我有一個帶有3個表(日誌數據)的MySQL數據庫。每張桌子都採用相同的結構。MySQL事件.csv輸出文件,名稱中帶有時間戳

現在我想編寫一個每6個月運行一次的事件,並導出csv文件中的所有行,這些行比半年早,並在第二個時間刪除它們。電影名稱應包括出口時間戳。

一開始我試圖表導出一個靜態名稱 - (較小的時間intervalls測試這裏)效果很好:

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
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 ; 
+0

感謝您的回答。當我使用你的Set-Statement時,我仍然有一個語法錯誤:缺少分號。 – Tony

+0

以及嘗試在最後應用分號雖然它的工作,即使沒有它對我來說 – Alexey

+0

只是很好檢查......你的'顯示完整processlist' contins事件調度? – Alexey

相關問題