日期:2014-05-18  浏览次数:20625 次

遍历多张表
我想问个问题,
  我有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 int

select @BeginDay=1,@EndDay=6

select @sql='with t as ('+char(10)

while(@BeginDay<=@EndDay)
begin
 select @sql=@sql+'select * from tb_'+cast(@BeginDay as varchar)+char(10)+'union all '+char(10)
 select @BeginDay=@BeginDay+1
end

select @sql=left(@sql,len(@sql)-12)+char(10)+') select * from t;'

-- 执行
exec(@sql)


-- 打印SQL
print @sql

--> 结果
with t as (
select * from tb_1
union all 
select * from tb_2
union all 
select * from tb_3
union all 
select * from tb_4
union all 
select * from tb_5
union all 
select * from tb_6
) select * from t;

------解决方案--------------------
SQL code

declare @num int 
set @num=1
declare @sql varchar(max)
set @sql=''
while @num<=101
begin
declare @str varchar(max)
set @str='select * from tbl'+cast(@num as varchar)+' union all'
set @num+@num+1
set @sql=@sql+@str
end
set @sql=left(@sql,len(@sql)-9)
exec(@sql)

这样你可以通过控制@num来实现查询的日期