Mysql: RENAME TABLE IF EXISTS

后端 未结 8 1263
甜味超标
甜味超标 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 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;
    

提交回复
热议问题