Create PROCEDURE AddOverUnderTmpFactor @IdHavaleh BIGINT , @ActionCode SMALLINT 
AS 
DECLARE @GuyCode VARCHAR(5)
SELECT @GuyCode = 
CASE
  WHEN LEN(Sender) = 5 THEN Sender
  ELSE Reciver
END FROM dbo.TmpHavaleh WHERE Id_Havaleh = @IdHavaleh

DECLARE @CacheOverUnder AS TABLE
(
  Radif INT,
  Id_Havaleh BIGINT,
  Name NVARCHAR(30),
  Code_Over_Under SMALLINT,
  Type CHAR(1),
  [Percent] REAL,
  Price money,
  Act_Code SMALLINT,
  ShowPrice CHAR(1),
  IsDuty Bit
)

 INSERT INTO @CacheOverUnder
 (
     Radif,
     Id_Havaleh,
     Name,
     Code_Over_Under,
     Type,
     [Percent],
     Price,
     Act_Code,
     ShowPrice,
     IsDuty
 )

-------------------------(Add Or Remove Value In Tmp_Over_Under_Factor)--------------------------
SELECT ROW_NUMBER() over (ORDER BY SortDisplay) Radif, 
       @IdHavaleh, Name, AutoId, type, Max_Percent, Max_Price,Act_Code,ShowPrice ,
Case
When (Formula is Null Or Formula = '') Then 0   
    Else                                                       
    Formula                                                
End as Price_Row
FROM dbo.Over_Under WHERE Action_Code = @ActionCode
AND Active = 1
AND AzTarikh <= CONVERT(VARCHAR(10),GETDATE(),111)
AND TaTarikh >= CONVERT(VARCHAR(10),GETDATE(),111)


 DELETE FROM dbo.Tmp_Over_Under_Factor WHERE Code_Over_Under NOT IN(SELECT Code_Over_Under FROM @CacheOverUnder)
 INSERT INTO dbo.Tmp_Over_Under_Factor
 (
     Id_Havaleh,
     Name,
     Code_Over_Under,
     Type,
     Act_Code,
     Auto_id_Havaleh,
     Price_Row,
     Max_Price,
     Max_percent,
	 Guy_Code,
     ShowPrice
 )
 SELECT Id_Havaleh,Name,Code_Over_Under,Type,Act_Code,Radif,IsDuty, Price,[Percent],@GuyCode, ShowPrice FROM @CacheOverUnder
 WHERE Code_Over_Under NOT IN(SELECT Code_Over_Under FROM dbo.Tmp_Over_Under_Factor WHERE Id_Havaleh = @IdHavaleh)
 ORDER BY Radif

