測試用的數(shù)據(jù)庫都是以“tb_”開頭的,可以先篩選查詢出要刪除的數(shù)據(jù)庫,再遍歷游標刪除數(shù)據(jù)庫。
delimiter //
drop procedure if exists drop_db;
CREATE PROCEDURE "drop_db"()
BEGIN
declare dynamicsql varchar(500);
declare tname varchar(64);
declare flag int default 0;
-- 打印要刪除的數(shù)據(jù)庫
select t.schema_name from information_schema.schemata t where t.schema_name like 'tb_%';
-- 定義游標
declare tnames cursor for select t.schema_name from information_schema.schemata t where t.schema_name like 'tb_%';
declare continue handler for not found set flag=1;
open tnames;
fetch tnames into name;
while flag <> 1 do
-- 拼接動態(tài)sql
set dynamicsql=concat('DROP DATABASE IF EXISTS ', tname);
set @executesql=dynamicsql;
prepare preparesql from @executesql;
excute preparesql;
DEALLOCATE prepare preparesql;
fetch tnames into tname;
end while;
close tnames;
END
//
call drop_db();