Mysql: RENAME TABLE IF EXISTS

后端 未结 8 1259
甜味超标
甜味超标 2020-12-10 01:08

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

Can anyone suggest a solution for this query?



        
相关标签:
8条回答
  • 2020-12-10 01:53

    There's no official solution yet. There has been feature request submitted in 2004, never closed

    0 讨论(0)
  • 2020-12-10 01:54

    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.

    0 讨论(0)
  • 2020-12-10 02:01

    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

    0 讨论(0)
  • 2020-12-10 02:03

    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

    0 讨论(0)
  • 2020-12-10 02:06

    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;
    
    0 讨论(0)
  • 2020-12-10 02:07
    create table table2 like table1;
    insert into table2 select * from table1;
    drop table table1;
    
    0 讨论(0)
提交回复
热议问题