CREATE Procedure [dbo].[Sp_RemoveDuplicateRowFactor] @id Bigint AS
BEGIN 
 IF Exists(Select K_code From TmpHavaleh
               Where Id_Havaleh = @id And Hamrah_Flag <> '1' 
               Group By K_Code
               Having COUNT(K_code)> 1) 
 Begin               
	 Begin Tran 
	 Update TmpHavaleh Set K_Qty1 = T.SumQty, Status = '1' From TmpHavaleh
	  inner join                                            
	 (                                                      
	 Select Sum(K_Qty1) SumQty, K_code, Price_Forosh, MIN(Autoid) MinAuto From TmpHavaleh     
	 Where Id_Havaleh =  @id AND Hamrah_Flag <> '1'
	 Group By K_Code, Price_Forosh                                       
	 Having COUNT(K_code)> 1                               
	 )As t on TmpHavaleh.AutoId = MinAuto AND Hamrah_Flag <> '1'              
	 IF @@ERROR > 0 
	   Rollback Tran

	DELETE TmpHavaleh FROM TmpHavaleh
	INNER JOIN 
	(
	SELECT Id_Havaleh,  K_code, Price_Forosh From TmpHavaleh          
					   WHERE Id_Havaleh = @id 
					   GROUP By K_Code, Price_Forosh, Id_Havaleh                        
					   HAVING COUNT(K_code)> 1
	) AS T ON T.Id_Havaleh = TmpHavaleh.Id_Havaleh AND T.K_Code = TmpHavaleh.K_Code AND T.Price_Forosh = TmpHavaleh.Price_Forosh
	WHERE IsNull(Status,0) <> '1' And Hamrah_Flag <> '1' 

    IF @@ERROR > 0 
	  Rollback Tran
				  


	Update TmpHavaleh set Radif = T.RowNo, Status = Null From TmpHavaleh
	Inner Join 
	(
	select (select count(*) from Tmphavaleh as Tmp 
			where Tmp.Autoid <= Tmphavaleh.Autoid
			And Id_Havaleh = @id
			) as RowNo, Tmphavaleh.K_Code
	from Tmphavaleh 
	Where Id_Havaleh = @id
	) As T on T.K_Code = TmpHavaleh.K_Code
	Where Id_Havaleh = @id
	Commit tran
  End
End
