CREATE TRIGGER [dbo].[Tu_Tolid]  ON  [dbo].[TmpHavaleh]
  
   AFTER UPDATE
AS 
BEGIN
	Declare @Autoid bigint
	Declare @Kind Varchar(3)
	Declare @TotPriceTolid money
	Declare @TmpK_Code varchar(15)
	Declare @Kqty money
	Declare @linkRecord bigint
	Declare @Id bigint
	Select @Id = TmpHeadh.Id_Havaleh,  @Kind = Kind_save , @autoid= Autoid, @TmpK_Code = K_Code, @linkRecord = Link_Record   From TmpHeadh inner join Inserted on Inserted.Id_Havaleh = TmpHeadh.Id_Havaleh
	Where Kind_Flag = 1 
   IF @Kind = '9'
   Begin
     Select @Kqty = K_Qty1, @TmpK_Code = K_Code From TmpHavaleh Where Link_Record = 0 And AutoId = @linkRecord
     
     Select @TotPriceTolid = Sum(Price_Kharid * K_Qty1) From TmpHavaleh 
					  Where Link_Record = @linkRecord 

     	       
	 SELECT  @TotPriceTolid = @TotPriceTolid/@Kqty 
	 

	 Update TmpHavaleh Set Price_KHarid = @TotPriceTolid
	 Where AutoId = @linkRecord
       
	 Update Anbar Set Price_Kharid = @TotPriceTolid Where K_Code = @TmpK_Code 
   End
End   
