CREATE PROCEDURE  [dbo].[Sp_Duty]  @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 = T2.SumFactor  - T1.SumUnder  + T1.SumOver  From (
  Select Id_Havaleh, IsNull(Sum(SumOver),0) SumOver , IsNull(Sum(SumUnder),0) SumUnder From ( 
  Select Id_Havaleh,  
  Sum(Case When Type = '1' Then Price End) SumOver,
  Sum(Case When Type = '0' Then price End) SumUnder 
  From Tmp_Over_Under_Row Inner Join TmpHavaleh
  On Tmp_Over_Under_Row.AutoId = TmpHavaleh.AutoId 
  Where Price_Row <> 1 And Id_Havaleh = @IdHavaleh And Takhfif_Flag = '1'
  Group By Id_Havaleh) As T1
  Group By Id_Havaleh) As T1

  Inner Join(
		Select TmpHeadH.Id_Havaleh, 
		Case
		  When Kind_Flag in ('5','7','9')              Then Sum(K_Qty1 * Price_Forosh)
		  When Kind_Flag in ('0','2','3', '4','6','8') Then Sum(K_Qty1 * PRice_Kharid)
		End As SumFactor
		From TmpHeadH Inner Join TmpHavaleh On TmpHavaleh.Id_Havaleh = TmpHeadH.Id_Havaleh
		Where TmpHeadH.Id_Havaleh = @IdHavaleh And Takhfif_Flag = '1'
                Group By Kind_Flag, TmpHeadH.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