当前位置: 代码迷 >> Sql Server >> 遍历多张表,该如何处理
  详细解决方案

遍历多张表,该如何处理

热度:70   发布时间:2016-04-27 13:28:37.0
遍历多张表
我想问个问题,
  我有10 张表,tb_1,tb_2,tb_3.......tb_10,表结构完全一样,只是时间不同
我想做个循环 多表查询 出 表1 到表10 的数据
  我怎么写呢??


我怎么做循环呢?
  比如 1表里面存的是 3月1号的数据,2表里存3月2号的, 10表存3月10号的。。 我怎么查 1到10号的数据呢?


时间不是固定的,我也可以查询1到5号的。。

------解决方案--------------------
探讨
select * from tb1 where convert(varchar(10),时间,120) between '2012-03-01' and '2012-03-10'
union all
select * from tb2 where convert(varchar(10),时间,120) between '2012-03-01' and '2012-
...
union al……

------解决方案--------------------
动态SQL实现,
SQL code
declare @sql varchar(6000),@BeginDay int,@EndDay intselect @BeginDay=1,@EndDay=6select @sql='with t as ('+char(10)while(@BeginDay<[email protected])begin select @[email protected]+'select * from tb_'+cast(@BeginDay as varchar)+char(10)+'union all '+char(10) select @[email protected]+1endselect @sql=left(@sql,len(@sql)-12)+char(10)+') select * from t;'-- 执行exec(@sql)-- 打印SQLprint @sql--> 结果with t as (select * from tb_1union all select * from tb_2union all select * from tb_3union all select * from tb_4union all select * from tb_5union all select * from tb_6) select * from t;
------解决方案--------------------
SQL code
declare @num int set @num=1declare @sql varchar(max)set @sql=''while @num<=101begindeclare @str varchar(max)set @str='select * from tbl'+cast(@num as varchar)+' union all'set @[email protected]+1set @[email protected][email protected]endset @sql=left(@sql,len(@sql)-9)exec(@sql)[email protected]
  相关解决方案