蜗牛背着沉重的壳,贴着地面一步步艰难地向前爬行,不回头,也不左顾右盼,只是朝着自己想到达的地方行进。
有时候需要从多张相同类型的表中提取数据,这些表有一些相同的列或者表结构完全相同,同时表名存在一定的规律,如果表数量少还好,如果表数量多的话则会比较繁琐。可以通过存储过程将多张表的数据提取到一张表的方法来降低工作量。
先创建测试表并生成测试数据。
以下存储过程创建10张测试表,每张表生成10条测试数据。
drop PROCEDURE if EXISTS create10tables;
create PROCEDURE create10tables()
BEGIN
DECLARE t_name VARCHAR(32);
DECLARE i INT;
DECLARE j INT;
DECLARE continue HANDLER for not found set t_name = "";
set i = 0;
set j = 0;
create_loop:LOOP
set i = i + 1;
set t_name = CONCAT("ttest",i);
set @dropsql = CONCAT(‘drop table if EXISTS ‘,t_name);
#select @dropsql;
prepare dropsql from @dropsql;
EXECUTE dropsql;
DEALLOCATE prepare dropsql;
set @createsql = concat(‘create table ‘,t_name,‘ (id int(11) not null auto_increment,modifytime timestamp null default current_timestamp,vdata varchar(32) ,primary key(id));‘);
#select @createsql;
prepare createsql from @createsql;
EXECUTE createsql;
DEALLOCATE prepare createsql;
insert_loop:LOOP
set j = j+1;
if j > 10 THEN
LEAVE insert_loop;
end if;
set @insertsql = concat(‘insert into ‘,t_name,‘(vdata) values(md5(rand()));‘);
#select @insertsql;
PREPARE insertsql from @insertsql;
EXECUTE insertsql;
deallocate PREPARE insertsql;
end LOOP insert_loop;
set j = 0;
if i > 10 THEN
LEAVE create_loop;
end if;
end LOOP create_loop;
END;
#执行create10tables 生成表与数据
call create10tables();
有了表和数据,可以在information_schema数据库的innodb_tables表中看到新生成的对应的表名。这里可以通过该表将所有的表名查出来,然后进行数据提取。SQL如下:
drop PROCEDURE if exists selectalldata;
drop table if exists t_test;
create PROCEDURE selectalldata()
BEGIN
DECLARE done int DEFAULT FALSE;
DECLARE t_name VARCHAR(32);
declare i int;
DECLARE cur1 CURSOR for SELECT table_name from information_schema.TABLES
where table_name like "ttest%";
DECLARE continue HANDLER for not found set done = TRUE;
open cur1;
set i = 0;
read_loop:LOOP
fetch cur1 into t_name;
if done THEN
LEAVE read_loop;
end if;
if i = 0 THEN
set @createsql = concat(‘create table t_test (id int(11) not null auto_increment,modifytime timestamp null default current_timestamp,vdata varchar(32) ,primary key(id));‘);
#select @createsql;
prepare createsql from @createsql;
EXECUTE createsql;
DEALLOCATE prepare createsql;
set i = i + 1;
end if;
set @insertsql = concat(‘insert into t_test(modifytime,vdata) select modifytime,vdata from ‘,t_name);
prepare insertsql from @insertsql;
EXECUTE insertsql;
DEALLOCATE prepare insertsql;
end LOOP;
close cur1;
END;
#执行selectdata
call selectalldata();
执行之后可以在t_test表中看到已经将所有的数据都提取出来了。
实际操作中,根据需要修改对应的SQL语句即可。
原文地址:http://blog.51cto.com/adwen2010/2142612