Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: RENAME TABLE IF EXISTS

Tags:

This DROP TABLE IF EXISTS works, too bad that RENAME TABLE IF EXISTS doesn't work.

Can anyone suggest a solution for this query?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS video_top_day TO video_top_day_for_delete' at line 1 

query:

RENAME TABLE IF EXISTS video_top_day TO video_top_day_for_delete 
like image 568
Somebody Avatar asked Feb 14 '12 15:02

Somebody


People also ask

How do I rename a table in MySQL?

The syntax to rename a table in MySQL is: ALTER TABLE table_name RENAME TO new_table_name; table_name. The table to rename.

When you use the MySQL rename table command the original table must be in which state?

The max length of a table name in MySQL is 64 characters. The old table (table_name_old) must exist in a database, and the new table (table_name_new) must not. To rename a table successfully, you must have ALTER and DROP privileges for the original table, and CREATE and INSERT privileges for the new table.


2 Answers

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; 
like image 154
Schiavini Avatar answered Oct 05 '22 12:10

Schiavini


First create table IF NOT EXISTS. Then RENAME it, so it will always exist!

Otherwise, rename the table, and if it doesn't exist just handle the error.

It is obvious, but it works.

like image 30
vulkanino Avatar answered Oct 05 '22 12:10

vulkanino