if exists(select 1 from sysobjects where name='p_calculate_init_settle')
  drop procedure p_calculate_init_settle
go


create procedure p_calculate_init_settle 
(
  @oper_date	varchar(10),
  @branch_no	varchar(6) ,
  @item_no		varchar(40),
  @real_qty		numeric(16,4)
)
as
begin
  if not exists(select 1 from t_da_jxc_daysum 
                  where oper_date >@oper_date and 
                   branch_no = @branch_no and
                   item_no = @item_no )
     return 
    declare @next_date varchar(10),
            @settle_amt numeric(16,4),
            @settle_amt2 numeric(16,4)
    UPDATE t_da_jxc_daysum 
	SET init_qty = init_qty - @real_qty,
		settle_qty=settle_qty - @real_qty,
		settle_amt= (settle_qty - @real_qty) * cost_price,
		settle_amt2 = (settle_qty - @real_qty) * pos_price
    WHERE oper_date >@oper_date and 
          branch_no = @branch_no and
          item_no = @item_no
          
    SELECT @settle_amt = settle_amt, @settle_amt2 = settle_amt2
	FROM t_da_jxc_daysum 
    WHERE oper_date = @oper_date and 
          branch_no = @branch_no and
          item_no = @item_no
          
     select @next_date=''
     SELECT @next_date = min(oper_date)
     FROM t_da_jxc_daysum 
     WHERE oper_date > @oper_date and 
          branch_no = @branch_no and
          item_no = @item_no

      WHILE LEN(@next_date) >0
      BEGIN
         UPDATE t_da_jxc_daysum 
			SET init_amt = @settle_amt,
				init_amt2=@settle_amt2
         WHERE oper_date=@next_date and branch_no=@branch_no and item_no=@item_no
                
         SELECT @settle_amt = settle_amt, @settle_amt2 = settle_amt2
         FROM t_da_jxc_daysum 
         WHERE oper_date = @next_date and 
             branch_no = @branch_no and
             item_no = @item_no

         SELECT @next_date = min(oper_date)
         FROM t_da_jxc_daysum 
         WHERE oper_date > @next_date and 
          branch_no = @branch_no and
          item_no = @item_no

         if @@ROWCOUNT = 0 break
     END
end
go