I have a MySQL server with many databases that have a similar table structure. When a piece of legacy software goes into an error state it writes a line to a few tables as well as emailing me. I am trying to write a simple SQL query to clear these tables down (TRUNCATE).
In my bash script I currently have:
mysql -e "SELECT CONCAT('TRUNCATE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';')
FROM information_schema.TABLES
WHERE TABLE_NAME IN ('errorLog', 'errorLogBacktrace', 'errorLogUrl');" |
grep -v 'CONCAT(' |
mysql
Line returns added to help with legibility hopefully.
But this does not appear to work and only executes the first TRUNCATE TABLE query generated by the above select.
The output from the select portion of the above code:
mysql -e "SELECT CONCAT('TRUNCATE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';')
FROM information_schema.TABLES
WHERE TABLE_NAME IN ('errorLog', 'errorLogBacktrace', 'errorLogUrl');" |
grep -v 'CONCAT('
is:
TRUNCATE TABLE db1.errorLog;
TRUNCATE TABLE db1.errorLogBacktrace;
TRUNCATE TABLE db1.errorLogUrl;
TRUNCATE TABLE db2.errorLog;
TRUNCATE TABLE db2.errorLogBacktrace;
TRUNCATE TABLE db2.errorLogUrl;
TRUNCATE TABLE db3.errorLog;
TRUNCATE TABLE db3.errorLogBacktrace;
TRUNCATE TABLE db3.errorLogUrl;
How can I get this to work? Do I need to loop over the lines and execute them one by one, if so how?
Looks like I was overcomplicating things. After some searching through serverfault I found: https://serverfault.com/questions/124797/alter-table-for-all-tables-in-a-database
So my command now looks like:
And with the appropriate MySQL escaping it should be:
Backticks escape keywords in the MySQL database and column names and the additional backslashes are to escape the backticks for bash as the string is being piped into the second MySQL process.