简体   繁体   中英

Dropping all schemas with no tables

I want to drop all databases with zero tables I was able to get the databases with tables using SELECT table_schema, count(table_name) FROM information_schema.tables group by table_schema But how can I delete the dbs not in this list. I can't do it manually because there are more then 500 dbs there.

About to know schemas without tables, you can try this:

SELECT * FROM information_schema.schemata S
WHERE NOT EXISTS
    (SELECT 'TABLE' from information_schema.tables T
     WHERE T.table_schema = S.schema_name)

Because in system table SCHEMATA you'll find all schemas of your server and in table TABLES you'll find all tables in all schemas

The upper query must be input on cursor, so you must use a prepared statement to execute your cursor, because your DROP DATABASE has a variable (your schema_table) and it can be ran only with a prepared statement

Used the method posted by @dnoeth in the comments with a slightly diffrent query to get the drop commands and then with some Notepad++ magic executed them to drop all empty databases

SELECT  concat('drop database ',schema_name) FROM information_schema.schemata 
WHERE schema_name NOT IN
(SELECT TABLE_SCHEMA FROM information_schema.tables)

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