16

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Desmond Liang
  • 2,210
  • 4
  • 26
  • 32
  • Either (1) live with the errors (2) create those tables everywhere, possible even in this .sql (create if not exists...) (3) write an little application that checks before truncate. – Wrikken Aug 19 '14 at 23:28
  • @Wrikken - cool. I thought you were being rude. But I see what you mean now. – Preet Sangha Aug 19 '14 at 23:37
  • @PreetSangha: well, you put me on a path, for which I thank you. I've commented on your answer what alterations need to be done to make it actually work. – Wrikken Aug 19 '14 at 23:42

3 Answers3

12

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
Community
  • 1
  • 1
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • 7
    Don't omit that (a) this needs to be in a function or procedure (b) you need a THEN & END IF (c) CALL the procedure and (d) DROP the procedure. – Wrikken Aug 19 '14 at 23:40
  • 17
    and if you have a second database with a table called `accesslog`, you're gonna have a bad time. – NDM May 19 '15 at 20:44
  • This is not SQL but from other comment "Stored program" – pdem May 30 '23 at 08:36
3

Example table name is Salaries: before TRUNCATE u can check records(select * from Salaries) After truncate it will reset identity too.

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Salaries')

begin

    TRUNCATE table Salaries;

end
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
ArulKumar
  • 39
  • 5
1

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 ;
Prabhjot Singh Kainth
  • 1,831
  • 2
  • 18
  • 26