This DROP TABLE IF EXISTS
works, too bad that RENAME TABLE IF EXISTS
doesn\'t work.
Can anyone suggest a solution for this query?
There's no official solution yet. There has been feature request submitted in 2004, never closed
Eight years after your question, MariaDB added the exact syntax you want in version 10.5.2: https://mariadb.com/kb/en/rename-table/
IF EXISTS
MariaDB starting with 10.5.2
If this is directive is used, one will not get an error if the table to be renamed doesn't exist.
If you don't want to keep variables you can do also this:
DELIMITER $$
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = database()
AND TABLE_NAME = 'oldname')
THEN
RENAME TABLE oldname to newname;
END if;
$$
DELIMITER ;
You can even further create a function if you want to reuse it
If you are familiar with PL/SQL, then you can check for existence of table by querying information_schema.columns and based on this perform rename
I've managed to execute a code that always works and generates no errors when the table doesn't exist:
SELECT Count(*)
INTO @exists
FROM information_schema.tables
WHERE table_schema = [DATABASE_NAME]
AND table_type = 'BASE TABLE'
AND table_name = 'video_top_day';
SET @query = If(@exists>0,
'RENAME TABLE video_top_day TO video_top_day_for_delete',
'SELECT \'nothing to rename\' status');
PREPARE stmt FROM @query;
EXECUTE stmt;
When you don't want to replace [DATABASE NAME]
manually you can use the following variable
SELECT DATABASE() INTO @db_name FROM DUAL;
create table table2 like table1;
insert into table2 select * from table1;
drop table table1;