CREATE PROCEDURE  [dbo].[Sp_Duty_Row]  @IdHavaleh Bigint , @AutoId numeric(18, 0)
AS
 iF (Select Count(Price_Row) Icount From Tmp_Over_Under_Row 
     Where Price_Row = 1 And ShowPrice = 1 And AutoId  = @AutoId) > 0 
 Begin

  Declare @TotPrice Money
  Select @TotPrice = IsNull(T2.SumRow,0)  - IsNull(T1.SumUnder,0)  + IsNull(T1.SumOver,0)  
  From (
        Select Id_Havaleh, AutoId, IsNull(Sum(SumOver),0) SumOver , IsNull(Sum(SumUnder),0) SumUnder From ( 
		Select Id_Havaleh, Tmp_Over_Under_Row.AutoId ,
		Sum(Case When Type = 1 Then Round(price,0) End ) SumOver,
		Sum(Case When Type = 0 Then Round(price,0) End ) SumUnder 
		From Tmp_Over_Under_Row
		Inner Join TmpHavaleh
		On TmpHavaleh.AutoId = Tmp_Over_Under_Row.AutoId
		Where Tmp_Over_Under_Row.AutoId = @AutoId And Price_Row <> 1
		Group BY Id_Havaleh, Tmp_Over_Under_Row.AutoId) As T1
		Group By Id_Havaleh,AutoId
	   ) As T1

  Inner Join(
		     Select TmpHeadH.Id_Havaleh, AutoId,
		     Case
		       When Kind_Flag in (5,7,9)              Then Round(K_Qty1 * Price_Forosh,0)
		       When Kind_Flag in (0,2,3,4,6,8) Then Round(K_Qty1 * PRice_Kharid,0)
		     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 T2 
            On T1.Id_Havaleh = T2.Id_Havaleh And T1.AutoId = T2.AutoId
            
            
  Declare @Id Bigint
  Declare @Percent decimal

  Declare CursorRow Cursor Local For
  Select [Percent], AutoId_Inc From Tmp_Over_Under_Row
  Where Price_Row = 1 And ShowPrice = 1 And AutoId = @AutoId
  Open CursorRow
  Fetch Next From CursorRow Into @Percent, @Id 
  While @@Fetch_Status = 0 
  Begin
    Update Tmp_Over_Under_Row Set Price = Round(@TotPrice * @Percent/100,0)
    Where AutoId_Inc = @Id 
    Fetch Next From CursorRow Into @Percent, @Id
  End
  Close CursorRow
  Deallocate  CursorRow
End