前言
這是工作中確實會用到,比如分庫分表后有t_order_01、t_order_02、t_order_03...t_order_08 這樣的表。
測試過程中造了大量數據進行測試,其中可能含有部分臟數據,因此下一輪測試時最好把整個模塊的數據進行刪除。
三月,你好。
實現SQL
采用了存儲過程來實現,可遍歷刪除這些特定前綴的表。
SQL如下:
## 存儲過程實現
drop PROCEDURE if EXISTS rush;
create PROCEDURE rush()
BEGIN
## 創建臨時表,插入快照數據
drop table if exists drop_tb;
create TEMPORARY table drop_tb(
rowNum int not null,
table_name VARCHAR(50) not null
);
insert into drop_tb
select @r := @r + 1 as rowNum,
table_name
from information_schema.TABLES as a,(select @r := 0 )as t
where table_schema = (select DATABASE())
and table_name like 'aopi_copy%'
order by a.table_name ;
## 變量設置
set @index = 0;
set @count = (select count(0) from drop_tb) ;
## 遍歷刪除前綴為 aopi_copy 的表
WHILE @index < @count DO
set @index = @index + 1 ;
set @tb_name = (
select table_name from drop_tb as ibn
where ibn.rowNum = @index
) ;
set @drop_sql_tax = concat('drop table if exists ',@tb_name);
PREPARE distSQL FROM @drop_sql_tax ;
EXECUTE distSQL;
DEALLOCATE PREPARE distSQL ;
END WHILE;
drop table drop_tb;
end ;
call rush();
drop PROCEDURE if exists rush;
## THE END
驗證流程
准備特定前綴八張表:
全選上述SQL並執行:
刷新表發現以aopi_copy 開頭的表全部被刪了。
當然這是drop table,你可以改成delete table,這樣就只會刪數據不會把表也刪掉了,所以具體還是看情況吧!