Create PROCEDURE  [dbo].[Sp_Duty_Factor]  @IdHavaleh Bigint 
AS
 iF (Select Count(Price_Row) Icount From Tmp_Over_Under_Factor 
     Where Price_Row = 1 And ShowPrice = 1 And Id_Havaleh = @IdHavaleh) > 0 
 Begin

  Declare @TotPrice Money
  Declare @Id Bigint
  Declare @Percent Real
 
  Select @TotPrice = IsNull(T2.SumRow,0)  - IsNull(T1.SumUnder,0)  + IsNull(T1.SumOver,0)  
  From (
  Select Id_Havaleh, IsNull(Sum(SumOver),0) SumOver , IsNull(Sum(SumUnder),0) SumUnder From ( 
  Select Tmpheadh.Id_Havaleh ,  
  Sum(Case When Tmp_Over_Under_Factor.Type = '1' Then Price End) SumOver,
  Sum(Case When Tmp_Over_Under_Factor.Type = '0' Then price End) SumUnder 
  From Tmp_Over_Under_Factor Inner Join TmpHeadH
  On Tmp_Over_Under_Factor.Id_Havaleh = TmpHeadH.Id_Havaleh
  Inner join Over_Under on Over_Under.AutoId = Tmp_Over_Under_Factor.Code_Over_Under
  Where Price_Row <> 1 And TmpHeadH.Id_Havaleh = @IdHavaleh  And Over_Under.Duty_Flag = '1'
  Group By Tmpheadh.Id_Havaleh
  ) As T1 Group By Id_Havaleh
  ) As T1
  
  Right Outer Join(
             Select Id_Havaleh, Sum(SumRow) SumRow From (
		     Select TmpHeadH.Id_Havaleh, 
		     Case
		       When Kind_Flag in ('5','7','9')              Then K_Qty1 * Price_Forosh
		       When Kind_Flag in ('0','2','3', '4','6','8') Then K_Qty1 * PRice_Kharid
		     End As SumRow
		     From TmpHeadH Inner Join TmpHavaleh On TmpHavaleh.Id_Havaleh = TmpHeadH.Id_Havaleh
		     Where TmpHeadH.Id_Havaleh = @IdHavaleh And Takhfif_Flag = '1'
		     ) As T Group By Id_Havaleh
           ) As T2 
            On T1.Id_Havaleh = T2.Id_Havaleh 


  Declare Cursor_Row Cursor Local For
  Select [Percent], AutoInc From Tmp_Over_Under_Factor 
  Where Price_Row = 1 And ShowPrice = 1 And Id_Havaleh = @IdHavaleh
  Open Cursor_Row
  Fetch Next From Cursor_Row Into @Percent, @Id 
  While @@Fetch_Status = 0 
  Begin
    Update Tmp_Over_Under_Factor Set Price = Round(@TotPrice * @Percent/100,0)
    Where Autoinc = @Id 
    Fetch Next From Cursor_Row Into @Percent, @Id 
  End
  Close Cursor_Row
  Deallocate  Cursor_Row
End
