如果数据库中没有表,请删除它

时间:2015-11-06 03:50:43

标签: mysql sql

是否有MySQL命令可以执行以下操作:

  

如果数据库中没有任何内容,请将其删除。如果其中有任何表格,则不执行任何操作。

如:

drop database if exists foobar

可是:

drop database if empty foobar

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

希望这对其他人也有帮助。在阅读了您的问题和评论员的评论后,我刚刚为自己的目的创建了一个程序。

use mysql;

-- switch to a different delimiter
delimiter $$

create procedure drop_empty_databases()
begin

    declare table_schema varchar(200); -- will hold schema obtained from query
    declare schema_end int default 0;  -- temp variable that's set to 1 when reading of all schema is done

    -- cursor that lists all schemas with no tables
    declare cur cursor for 
        select s.schema_name
        from information_schema.schemata s
        left join information_schema.tables t on t.table_schema = s.schema_name
        group by s.schema_name
        having count(t.table_name) = 0;

    -- set schema_end to 1 when we run out of schemas while looping
    declare continue handler for not found set schema_end = 1;

    open cur;
    looper: loop
        fetch cur into table_schema;
        if schema_end = 1 then
            leave looper;
        end if;

        set @sql = concat('drop database ', table_schema);
        prepare stmt from @sql;
        execute stmt;
    end loop;
    close cur;

end
$$

-- switch back to semi-colon delimiter
delimiter ;

用法:

use mysql;
create database test123;
call drop_empty_databases();  -- test123 database should be gone after running this

请在生产服务器上进行测试,并确认它符合您的要求。

答案 1 :(得分:1)

正如Barmar所说,你可以使用INFORMATION_SCHEMA.TABLES存储过程。

这是我的小努力:

DELIMITER //
CREATE PROCEDURE spDropDB_IF_Empty()
BEGIN

IF (SELECT COUNT(table_name) from INFORMATION_SCHEMA.tables
    WHERE Table_Schema = 'mariadb')= 0 THEN

    DROP DATABASE mariadb;

ELSE
    SELECT 'There are tables in the mariaDB';
END IF;
END //
DELIMITER ;

致电SP:

CALL spDropDB_IF_Empty()