I am storing my sql operation logs in a table sync_logger, and I want to save these logs to regular file periodically. In order to do so, I tried to create a event scheduler. but I always get following error at select statement.
MariaDB [sync]> DELIMITER !!
MariaDB [sync]> CREATE EVENT IF NOT EXISTS write_to_log_event
-> ON SCHEDULE
-> EVERY 1 DAY
-> DO
-> BEGIN
-> DECLARE log_file VARCHAR(255);
-> SET log_file = CONCAT('/var/log/sync_db_log_' ,DATE_FORMAT(NOW(), '%Y%m%d%H%i%S'));
-> SELECT * INTO OUTFILE log_file from sync_logger;
-> DELETE FROM sync_logger;
-> END;
-> !!
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'log_file from sync_logger;
DELETE FROM sync_logger;
END' at line 8
MariaDB [sync]> delimiter ;
I can't figure out what the problem is. Can anyone help?
The name of output file is a literal, not a parameter, and it won't be replaced with variable value. Also the filename must be quoted.
Use prepared statement:
CREATE EVENT IF NOT EXISTS write_to_log_event
ON SCHEDULE
EVERY 1 DAY
DO
BEGIN
SET @write_to_log_event_sql := CONCAT('SELECT * INTO OUTFILE ''/var/log/sync_db_log_' ,
DATE_FORMAT(NOW(), '%Y%m%d%H%i%S'),
''' FROM sync_logger');
-- SELECT @write_to_log_event_sql; -- for debugging purposes
PREPARE stmt FROM @write_to_log_event_sql;
EXECUTE stmt;
DROP PREPARE stmt;
TRUNCATE sync_logger;
END
PS. TRUNCATE is faster than DELETE.
It works. Thank you very much.