CREATE PROCEDURE  [dbo].[Sp_Duty_Row]  @IdHavaleh Bigint , @AutoId numeric(18, 0), @ActionCode tinyint
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)  - Abs(TotOverUnder)
  From (
SELECT Tmp_Over_Under_Row.Autoid, 
(SUM(CASE WHEN dbo.Tmp_Over_Under_Row.Type = 1 THEN price ELSE 0 END) - SUM(CASE WHEN Tmp_Over_Under_Row.Type = 0 THEN price ELSE 0 END)) TotOverUnder
FROM dbo.Tmp_Over_Under_Row
INNER JOIN dbo.Over_Under ON OVER_Under.AutoId = Code_Over_Under
WHERE dbo.Tmp_Over_Under_Row.Autoid = @AutoId
AND dbo.Over_Under.Duty_Flag = 1
AND Action_Code = @ActionCode AND Price_Row <> 1
GROUP BY Tmp_Over_Under_Row.AutoId
) AS T1
Inner Join(
		     Select TmpHeadH.Id_Havaleh, AutoId,
		     Case
		       When Kind_Flag in (5,9,7,0,6) THEN Round(K_Qty1 * Price_Forosh,0)
		       When Kind_Flag in (2,3,4,8)   THEN Round(K_Qty1 * Price_Kharid,0)
		     End As SumRow
		     From TmpHeadH Inner Join TmpHavaleh On TmpHavaleh.Id_Havaleh = TmpHeadH.Id_Havaleh
		     Where dbo.TmpHavaleh.Autoid = @AutoId AND Takhfif_Flag = 1
           ) As T2 
            On T1.AutoId = T2.AutoId


  
  IF ISNULL(@TotPrice,0) > 0 
  Begin
	  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
End

