本段代码主要为了记录存储过程以及游标的使用,防止以后自己忘记
知识点:1、存储过程书写
2、游标书写
3、游标循环更新记录
create proc saletarget
as
declare @oweridname varchar(20)
declare @hmp_fiscalyear int
declare @hmp_businessunitidname varchar(20)
declare @hmp_nationterritoryidname varchar(20)
declare @hmp_currentyeartargetwithvat decimal(18,2)
declare @hmp_month int
declare @hmp_taxtargetamount decimal(18,2)
declare @quarters varchar(10)
declare @ac decimal(18,2)
declare @saleach decimal(10,2)
declare @yaact decimal(18,2)
declare @growth decimal(10,2)
declare @hmp_salestargetdetailId varchar(50)
begin
select * into #temp from(select A.OwnerIdName,A.hmp_fiscalyear,hmp_BusinessUnitIdName,hmp_nationterritoryidName,isnull(hmp_currentyeartargetwithvat,0) as hmp_currentyeartargetwithvat,hmp_month,isnull(hmp_taxtargetamount,0) as hmp_taxtargetamount,cast('' as varchar(10)) as quarters,cast(0 as decimal(18,2)) as ac,cast(0 as decimal(10,2)) as saleach,cast(0 as decimal(18,2)) as yaact,cast(0 as decimal(10,2)) as growth,b.hmp_salestargetdetailId from hmp_target A INNER JOIN hmp_salestargetdetail B ON A.hmp_targetId = B.hmp_targetid where hmp_month is not null)a
DECLARE mycursor CURSOR
FOR
select * from #temp
open mycursor
fetch next from mycursor into @oweridname,@hmp_fiscalyear,@hmp_businessunitidname,@hmp_nationterritoryidname,@hmp_currentyeartargetwithvat,@hmp_month,@hmp_taxtargetamount,@quarters,@ac,@saleach,@yaact,@growth,@hmp_salestargetdetailId
--判断游标的状态
-- 0 fetch语句成功
---1 fetch语句失败或此行不在结果集中
---2 被提取的行不存在
WHILE (@@fetch_status = 0)
begin
--获取本月完成数
select @ac = SUM(hmp_totaltaxprices) from hmp_deliverylistorder where hmp_SystemUseridName = @oweridname and hmp_deliverydate>=dateadd(month, datediff(month, 0, @hmp_fiscalyear+'-'+@hmp_month+'-01'), 0) and hmp_deliverydate<=dateadd(month, datediff(month, 0, dateadd(month, 1, @hmp_fiscalyear+'-'+@hmp_month+'-01')), -1)
--获取去年同期完成数
select @yaact = SUM(hmp_totaltaxprices) from hmp_deliverylistorder where hmp_SystemUseridName = @oweridname and hmp_deliverydate>=dateadd(yy,-1,dateadd(month, datediff(month, 0, @hmp_fiscalyear+'-'+@hmp_month+'-01'), 0)) and hmp_deliverydate<=dateadd(yy,-1,dateadd(month, datediff(month, 0, dateadd(month, 1, @hmp_fiscalyear+'-'+@hmp_month+'-01')), -1))
--目标完成率
if @hmp_taxtargetamount>0
set @saleach = @ac/@hmp_taxtargetamount*100
else
set @saleach = 0
--增长率
if @yaact>0
set @growth = (@ac-@yaact)/@yaact*100
else
set @growth = 0
update #temp set ac=@ac,saleach=@saleach,yaact=@yaact,growth=@growth where hmp_salestargetdetailId=@hmp_salestargetdetailId
fetch next from mycursor into @oweridname,@hmp_fiscalyear,@hmp_businessunitidname,@hmp_nationterritoryidname,@hmp_currentyeartargetwithvat,@hmp_month,@hmp_taxtargetamount,@quarters,@ac,@saleach,@yaact,@growth,@hmp_salestargetdetailId
end
close mycursor
deallocate mycursor
select * from #temp
end