CREATE  TRIGGER [dbo].[TU_TotPrice] ON [dbo].[Havaleh]
AFTER Update
As
	IF Update(K_Qty1) Or UPDATE(Price_Kharid) Or UPDATE(Price_Forosh) Or UPDATE(Price_Omdeh)
	Begin
		Declare @Id Bigint
		Select @Id = Id_Havaleh From Inserted Group By Id_Havaleh
	    
		Update HeadH Set 
		Tot_Price_KHarid = T.TotPriceKharid ,
		Tot_Price_forosh = T.TotPriceForosh ,
		Tot_Price_Omdeh = T.TotPriceOmdeh ,
		Tot_Price_Cooperative =
		Case
		  When Kind_Flag in (2,3,4,8)    then PriceKharidCooperative
		  When Kind_Flag in (5,7,9,0,6)  then PriceForoshCooperative
		End ,
		Kind_Cooperative = 
		Case
		  When T.KindCooperative > 0 Then Cast(Kind_Flag As TinyInt) + 900
		  Else
			0
		End
		From HeadH 
		Inner Join (
					 Select Id_Havaleh, 
					 Sum(Round(K_Qty1 * Price_kharid,0)) TotPriceKharid,      
					 Sum(Case When IsNull(Cooperative_Flag,0) = '1' Then Round(K_Qty1 * Price_KHarid,0) Else 0 End) PriceKharidCooperative,
					 Sum(Case When IsNull(Cooperative_Flag,0) = '1' Then Round(K_Qty1 * Price_Forosh,0) Else 0 End) PriceForoshCooperative,
					 Sum(Round(K_Qty1 * Price_Forosh,0)) TotPriceForosh,
					 Sum(Round(K_Qty1 * Price_Omdeh,0)) TotPriceOmdeh,
					 Sum(Cast(IsNull(Cooperative_Flag,0) as int)) KindCooperative
					 From Havaleh  
					 Where Id_Havaleh = @Id
					 Group By Id_Havaleh
				  ) As T on headh.Id_Havaleh  =T.Id_Havaleh      
		Where Headh.Id_Havaleh = @id
    End
