Create TRIGGER [dbo].[TU_TotPriceHeadH] ON [dbo].[headH] 
For Update AS  
Declare @Tot_Price_Kharid   Money 
Declare @Tot_Price_Omdeh    Money 
Declare @Tot_Price_Forosh   Money 
Declare @Tot_Price_Cooperative   Money 
Declare @Tot_Price          Money 
Declare @Nu                 Bigint 
Declare @Kind_flag          Char(1)
IF Update(Tot_Price_Forosh)Or Update(Tot_Price_Kharid)  Or Update(Tot_Price_Omdeh) 
begin   
  Select @Nu=i.Id_Havaleh,@Tot_Price_Forosh=i.Tot_Price_Forosh  ,  
         @Tot_Price_Kharid=i.Tot_Price_Kharid,@Tot_Price_Omdeh=i.Tot_Price_Omdeh,
         @Tot_Price_Cooperative = Tot_Price_Cooperative,  
         @Kind_Flag=i.Kind_Flag from inserted i where Id_Havaleh=i.Id_havaleh  
         
  Set @Tot_Price=0 
  if  @Kind_Flag= '0'  Set @Tot_Price=@Tot_Price_Forosh 
  if  @Kind_Flag= '2'  Set @Tot_Price=@Tot_Price_Kharid 
  if  @Kind_Flag= '3'  Set @Tot_Price=@Tot_Price_Kharid 
  if  @Kind_Flag= '4'  Set @Tot_Price=@Tot_Price_Kharid 
  if  @Kind_Flag= '5'  Set @Tot_Price=@Tot_Price_Forosh 
  if  @Kind_Flag= '6'  Set @Tot_Price=@Tot_Price_Forosh 
  if  @Kind_Flag= '7'  Set @Tot_Price=@Tot_Price_Forosh 
  if  @Kind_Flag= '8'  Set @Tot_Price=@Tot_Price_Kharid 
  if  @Kind_Flag= '9'  Set @Tot_Price=@Tot_Price_Forosh 
  IF @Tot_Price <> 0 
  begin  
    Update Sanad Set Nu_Cooperative = CAST(@Kind_Flag as Smallint) 
    Where (Nu_Cooperative is Null  Or  Nu_Cooperative = '') And Nu_Havaleh = @Nu 
    
    IF Exists(Select Nu_Cooperative From Sanad Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint) + 900) And Nu_Havaleh = @Nu)  -- مشارکتي
    Begin
      IF  @Tot_Price_Cooperative   = 0      
         Delete From Sanad Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint) + 900) And Nu_Havaleh = @Nu
      Else
      Begin
        Update dbo.sanad set Bedeh=@Tot_Price_Cooperative  
        Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint) + 900) And BESTAN = 0  And Nu_Havaleh = @Nu
        Update dbo.sanad set Bestan=@Tot_Price_Cooperative 
        Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint) + 900) And BEDEH  = 0 And Nu_Havaleh = @Nu
        Set @Tot_Price = @Tot_Price - @Tot_Price_Cooperative
      End
    End

    IF Exists(Select Nu_Cooperative From Sanad Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint)) And Nu_Havaleh = @Nu)
    Begin
      IF @Tot_Price = 0 
         Delete From Sanad Where Nu_Cooperative = (CAST(@Kind_Flag as Smallint)) And Nu_Havaleh = @Nu
      Else
      Begin
        Update dbo.sanad set Bedeh=@Tot_Price   Where IsNull(Nu_Cooperative, @Kind_Flag) = @Kind_Flag  And BESTAN = 0  
        And Nu_Havaleh = @Nu And Nu_Over_Under Is Null And Nu_Ghest is Null
        Update dbo.sanad set Bestan=@Tot_Price  Where IsNull(Nu_Cooperative, @Kind_Flag) = @Kind_Flag  And BEDEH = 0
        And Nu_Havaleh = @Nu And Nu_Over_Under Is Null And Nu_Ghest is Null
      End
    End
  end 
 end
