I have a .sql file that clear cached data in a mysql schema before export because the cached data in these tables is useless when I import the export file to a different server. I use this script on multiple sites, but in some instances certain table don't exist because they are not required. How do I only truncate a table in MySQL if only that table exist?
TRUNCATE accesslog;
TRUNCATE cache;
TRUNCATE cache_block;
TRUNCATE cache_bootstrap;
TRUNCATE cache_customfilter;
TRUNCATE cache_field;
TRUNCATE cache_filter;
TRUNCATE cache_form;
TRUNCATE cache_image;
TRUNCATE cache_menu;
TRUNCATE cache_metatag;
TRUNCATE cache_page;
TRUNCATE cache_path;
TRUNCATE cache_token;
TRUNCATE cache_update;
TRUNCATE cache_views;
TRUNCATE cache_views_data;
TRUNCATE watchdog;
Thanks in advance.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
TRUNCATE TABLE doesn't log the transaction. That means it is lightning fast for large tables. The downside is that you can't undo the operation. DELETE FROM logs each row that is being deleted in the transaction logs so the operation takes a while and causes your transaction logs to grow dramatically.
Typically, TRUNCATE TABLE quickly deletes all records in a table by deallocating the data pages used by the table. This reduces the resource overhead of logging the deletions, as well as the number of locks acquired. Records removed this way cannot be restored in a rollback operation.
See this answer on Using the IF Statement to do a conditional insert:
Can you do the same using the ANSI INFORMATION_SCHEMA
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'accesslog')
TRUNCATE accesslog
You can try this stored procedure as it is really difficult without it.
CREATE PROCEDURE tbl_delete(IN table_name CHAR(255),IN database_name CHAR(255))
BEGIN
IF @table_name IN (SELECT table_name FROM information_schema.tables WHERE table_schema = database_name)
THEN
SET @query = CONCAT("TRUNCATE TABLE ", @database_name, ".", @table_name);
PREPARE stmt FROM @query;
EXECUTE stmt;
END IF;
END ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With