drop procedure if exists mergeTable;
CREATE PROCEDURE mergeTable()
BEGIN
#定义变量
declare temp_table_name varchar(20);
declare total int default 0;
declare done int default false;
#游标数据来源 查询出你想要合并的表名称
declare cur cursor for SELECT table_name
from information_schema.TABLES
where table_name LIKE '%user%'
group by table_name;
#定义标记结束
declare continue HANDLER for not found set done = true;
drop table if exists temp_table;
#创建临时表
CREATE temporary TABLE `temp_table`
(
`id` int(11) NOT NULL,
`name` int(11) NOT NULL,
`type` tinyint(2) NOT NULL
);
set total = 0;
open cur;
#变量赋值
fetch cur into temp_table_name;
while(not done)
do
#复制表数据到临时表
set @sqlStr = CONCAT('INSERT INTO temp_table (`id`, `name`, `type`)
SELECT `id`, `name`, `type`
FROM ', temp_table_name);
PREPARE stmt from @sqlStr;
#执行sql
EXECUTE stmt;
fetch cur into temp_table_name;
end while;
close cur;
#统计临时表个数
select count(1) from temp_table;
END;
#执行临时表
call mergeTable();