select sum(sl)
from MZ_F040101
where ypdm='52' and ysdm='4902'
union all 
select sum(sl)
from MZ_F04012
where ypdm='52' and ysdm='4902'

解决方案 »

  1.   

    declare @tablename varchar(30),i int
    select * from sysobjects where type='u' and name like 'MZ_F0401'
    set i=@@rowcount
    if exists(select * from sysobjects where type='u' and id=object_id(##tmp))
    drop table #tmp
    else
        select sum(sl) into ##tmp from MZ_F040101 where where 1<>1while i>0 
    beginexec('insert into ##tmp
    select sum(sl)
    from ['+@tablename+']
    where ypdm=''52'' and ysdm=''4902''')set i=i-1
    end
    select * from ##tmp
    drop table ##tmp
      

  2.   

    create proc test_query @begindate varchar(6), @enddate varchar(6)
    as
    --declare @begindate varchar(6), @enddate varchar(6)
    declare @now varchar(6), @str varchar(8000)
    set @begindate='040101'
    set @enddate='040131'
    set @now=@begindate
    set @str=''
    while @now<=@enddate
    begin
    set @str=@str+'union select sum(sl) as sumall from MZ_F'+@now+' where ypdm=''52'' and ysdm=''4902'''
    set @now=right(convert(varchar(8),dateadd(d,1,convert(datetime, @now)),112),6)
    end
    set @str='select sum(sumall) from ('+stuff(@str,1,6,'')+') a'
    exec(@str)
    --同样未测试,但sql语句应该没有问题