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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值