sql server游标实例:使用游标、临时表从多张表查询数据

本实例表Item按照月份会分成Item201901、Item201902这样的每月一张表,那要怎么跨月自由查询时间段的数据呢。

create Procedure P_ShopTaotal  @End date with encryption as
declare @str nvarchar(max), @table varchar(50)
--创建临时表
select OrgCode, sum(PluTotal) PluTotal into #P_ShopTaotal from SYSDBSX.dbo.Item201901
where 1<>1
group by OrgCode, PluCode
--游标的使用
declare _c1 cursor for select name from SYSDBSX.dbo.sysobjects where [type]='U' and name like 'Item20%'
open _c1
fetch next from _c1 into @table
while @@fetch_status=0 begin
--print @table
	set @str='insert #P_ShopTaotal select OrgCode,  sum(PluTotal) PluTotal from SYSDBSX.dbo.'+@table+' where OrgCode<>''C001'' and SDate >= ''2018-11-18'' and SDate <= '''+convert(varchar(20), @End, 120)+''' and ItemType<>''V'' group by OrgCode'
--print @str
	exec sp_executesql @str
	fetch next from _c1 into @table
end
close _c1
deallocate _c1
select a.OrgCode, b.OrgName, a.PluTotal from (
select OrgCode, sum(PluTotal) PluTotal from #P_ShopTaotal group by OrgCode
) a left join SYSDBSX.dbo.SubShop b on a.OrgCode=b.OrgCode
order by a.PluTotal desc
drop table #P_ShopTaotal

猜你喜欢

转载自blog.csdn.net/jeesr/article/details/87854527