mysql使用存储过程将多条(4条以上)SQL使用 union all 合并
查询一些的表的数据,因为表名的后几位是不固定的,并且没有都有一个新表建立,所以就使用存储过程,动态的生成了所有的表名。但是,call出来的结果不是在一块的,每个表是每个表...
查询一些的表的数据,因为表名的后几位是不固定的,并且没有都有一个新表建立,所以就使用存储过程,动态的生成了所有的表名。但是,call出来的结果不是在一块的,每个表是每个表的数据,没有把所有表的数据放到一块,想使用union all合并,但是失败了。。。求高手帮忙,怎么动态的把多个表的数据查出,用一个表来展示,不能使用insert。。(下附sql);
BEGIN
declare sel_sql VARCHAR(100);
declare g_sql VARCHAR(100);
declare u_sql VARCHAR(100);
declare t_name VARCHAR(100);
DECLARE done INT DEFAULT FALSE;
declare month_cursor CURSOR for select month from fee_month where flag=1;
declare CONTINUE HANDLER for not found set done=true;
set sel_sql='select sum(fee + fee2 + fee3) As fee,month from fee_detail_';
set g_sql=' group by month ';
set u_sql='union all ';
OPEN month_cursor;
my_loop:loop
FETCH month_cursor into t_name;
if done then
leave my_loop;
end if;
set @s_sql= CONCAT(sel_sql,t_name,g_sql);
PREPARE pre_s_sql from @s_sql;
EXECUTE pre_s_sql;
deallocate prepare pre_s_sql;
end loop;
close month_cursor;
END 展开
BEGIN
declare sel_sql VARCHAR(100);
declare g_sql VARCHAR(100);
declare u_sql VARCHAR(100);
declare t_name VARCHAR(100);
DECLARE done INT DEFAULT FALSE;
declare month_cursor CURSOR for select month from fee_month where flag=1;
declare CONTINUE HANDLER for not found set done=true;
set sel_sql='select sum(fee + fee2 + fee3) As fee,month from fee_detail_';
set g_sql=' group by month ';
set u_sql='union all ';
OPEN month_cursor;
my_loop:loop
FETCH month_cursor into t_name;
if done then
leave my_loop;
end if;
set @s_sql= CONCAT(sel_sql,t_name,g_sql);
PREPARE pre_s_sql from @s_sql;
EXECUTE pre_s_sql;
deallocate prepare pre_s_sql;
end loop;
close month_cursor;
END 展开
1个回答
展开全部
BEGIN
declare sel_sql VARCHAR(100);
declare g_sql VARCHAR(100);
declare u_sql VARCHAR(100);
declare t_name VARCHAR(100);
DECLARE done INT DEFAULT FALSE;
declare month_cursor CURSOR for select month from fee_month where flag=1;
declare CONTINUE HANDLER for not found set done=true;
set sel_sql='(select sum(fee + fee2 + fee3) As fee,month from fee_detail_';/*左括弧*/
set g_sql=' group by month ) ';/*右括弧*/
set u_sql=' union all ';/*加空格、上同*/
OPEN month_cursor;
my_loop:loop
FETCH month_cursor into t_name;
if done then
leave my_loop;
end if;
if s_sql is null then
set @s_sql= CONCAT(sel_sql,t_name,g_sql);/*第一个SQL*/
else
set @s_sql= CONCAT(s_sql, u_sql, sel_sql, t_name, g_sql);/*开始Union后续SQL*/
end if;
end loop;
/*最后执行一次拼接后的SQL语句*/
PREPARE pre_s_sql from @s_sql;
EXECUTE pre_s_sql;
deallocate prepare pre_s_sql;
close month_cursor;
END
思路修正,貌似还有不少语法问题,自行修复。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询