CREATE  TRIGGER [dbo].[TD_TotPrice] ON [dbo].[Havaleh]
AFTER Delete
As
	Declare @Id Bigint
    Select @Id = Id_Havaleh From Deleted Group By Id_Havaleh
    
    IF Not Exists(Select Id_Havaleh From Havaleh Where Id_Havaleh = @Id)
      Update HeadH Set Tot_Price_KHarid = 0 , Tot_Price_forosh = 0 , 
                          Tot_Price_Omdeh = 0 , Tot_Price_Cooperative = 0,
                          Kind_Cooperative = 0
      Where Id_Havaleh = @id
    
    
	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
