Create PROCEDURE  [dbo].[Sp_Duty]  @IdHavaleh Bigint , @TotDuty VARCHAR(10), @ActionCode TinyInt
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(@TotDuty,0) - Abs(SUM(CASE WHEN Tmp_Over_Under_Factor.Type = 1 THEN price ELSE 0 END) - SUM(CASE WHEN Tmp_Over_Under_Factor.Type = 0 THEN price ELSE 0 END)) 
	FROM dbo.Tmp_Over_Under_Factor
	INNER JOIN dbo.Over_Under ON OVER_Under.AutoId = Code_Over_Under
	WHERE Id_Havaleh=  Id_Havaleh
	AND Price_Row <> 1
	AND dbo.Over_Under.Duty_Flag = 1
	AND Action_Code = @ActionCode
	GROUP BY Id_Havaleh
	Select @TotPrice

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