Fork me on GitHub

MYSQL 批量删除以特定前缀开头的表

前言

这是工作中确实会用到,比如分库分表后有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,这样就只会删数据不会把表也删掉了,所以具体还是看情况吧!
posted @ 2021-03-29 14:52  竹根七  阅读(1337)  评论(1编辑  收藏  举报