简体   繁体   中英

How do I check if table exists before alter table

I need query to update all tables and set ENGINE = INNODB To many databases. But some of the databases don't have all the same tables; some databases have more tables than others.

So the problem is that

ALTER TABLE `ads` ENGINE = INNODB;
ALTER TABLE `modules` ENGINE = INNODB;
ALTER TABLE `ad_extras` ENGINE = INNODB;

Throws an error when the table modules doe snot exist. I see that I cannot make a direct IF statement' I tried:

IF EXISTS (SHOW TABLES LIKE 'modules') BEGIN
ALTER TABLE `modules` ENGINE = INNODB;
END IF

But it throws

Unrecognized statement type (near IF EXISTS)

Any ideas?

If this is just an ad-hoc task,

select concat('ALTER ', TABLE_NAME, " ENGINE = INNODB;") 
from information_schema.TABLES 
where TABLE_SCHEMA = '<your schema>';

Execute the output again.

If Exists works only in a stored procedure.

a fixed edition of Jacob's answer:

SET SESSION group_concat_max_len = 1000000;

select group_concat(concat('ALTER Table ', TABLE_NAME, ' ENGINE = INNODB;') SEPARATOR '\n')
from information_schema.TABLES 
where TABLE_SCHEMA = 'your_schema_name' and TABLE_TYPE<>'VIEW';

This will give you a script to copy and run separately.

像这个查询一样简单地测试怎么样:

DROP TABLE IF EXISTS `yourtablename`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM