有一数据库,cawsServer 有许多表,这些表都是以站点命名的,比如HM001,HM002,HM003...
表的内容为 如:表HM001 
站号          时间                  雨量
HM001    2013-07-13 08:00:00         3
HM001    2013-07-13 09:00:00         4
请问如何把HM开头的表按某一个查询时间合并起来形成一个大表,以方便查询
如:HM001    2013-07-13 08:00:00         3
    HM002    2013-07-13 08:00:00         5多表SQL

解决方案 »

  1.   


    declare @SQL varchar(max)
    set  @SQL = ''
    select @SQL = @SQL+ 'select 站号,时间  ,雨量 from '+name+' union all '
    from sysobjects
    where name like 'HM%'
    and xtype = 'U'
    set @SQL = left(@SQL,len(@SQL)-len( 'union all '))
    --print @SQL
    exec(@SQL)
      

  2.   

    declare @sql varchar(2000)
    set @sql=''
    select @sql=@sql+case when row=1 then '' else ' union all ' end
    +' select * from '+name 
    from (
    select name,row_number() over(order by name) as row from sysobjects 
    where xtype='T' and name like 'HM%'
    )t
    print @sql
      

  3.   


    declare @SQL varchar(max)
    set  @SQL = ''
    select @SQL = @SQL+ 'select 站号,时间  ,雨量 from '+name+' union all '
    from sysobjects
    where name like 'HM%'
    and xtype = 'U'
    set @SQL = left(@SQL,len(@SQL)-len( 'union all '))
    --print @SQL
    exec(@SQL)

    简单明了 MARK
      

  4.   

    我运行通过过,但我只取某个时段的所有表合并,该如何写?如取2013-07-13 08:00:00
    declare @Firsttimes varchar(20)
    set @Firsttimes='2013-07-13 08:00:00'
    set  @SQL = ''select @SQL = @SQL+ 'select SID,TT ,BA from ['+name+'] and TT='''+ @Firsttimes +''' union all 'from sysobjects 
    where name like 'HM%'and xtype = 'U'
    set @SQL = left(@SQL,len(@SQL)-len( 'union all '))
    --print @SQL 
    exec(@SQL) 
    出错,因为有100多个表,@SQL 
    可能超过字段长度吧
      

  5.   

    这个只能用动态语句进行哦,先找出表再用Union处理