
Create TRIGGER [dbo].[TU_Ghest] ON [dbo].[Ghest] 
FOR UPDATE
AS
  Declare   @Nu_Ghest      BigInt 
  Declare   @Aghsat_Nu     BigInt 
  Declare   @msg           Bigint
  Declare   @Act           Smallint 
  Declare   @Guy_Code      VarChar(20)
  Declare   @Price         Money
  Declare   @Note          VarChar(50)
  Declare   @Autoid        Bigint
  Declare   @Bestan        Money
  Declare   @IdSanad       Bigint
  declare   @MonthGhest nvarchar(30)
  declare   @userId     smallint



Select @Autoid = Deleted.Autoid , @Bestan = Inserted.Bestan , @IdSanad = Inserted.IdSanad,@userId=Inserted.User_Id From Deleted , Inserted 

If Update( BEDEH )
    Begin
      Update dbo.HeadGh set T_BEDEH = T_BEDEH - (Select Sum(Bedeh) from Deleted) From Deleted
      Where   dbo.HeadGh.Id_Ghest = Deleted.Id_Ghest
      update dbo.HeadGh set T_BEDEH = T_BEDEH + (Select Sum(Bedeh) from inserted) From Inserted
       Where   dbo.HeadGh.Id_Ghest = inserted.Id_Ghest
    End	

If Update( BESTAN ) 
    Begin
       Update dbo.HeadGh set T_BESTAN = T_BESTAN - (Select Sum(Bestan) from Deleted) From deleted 
       Where   dbo.HeadGh.Id_Ghest = Deleted.Id_Ghest
       update dbo.HeadGh set T_BESTAN = T_BESTAN + (Select Sum(Bestan) from inserted) From inserted 
       Where   dbo.HeadGh.Id_Ghest = inserted.Id_Ghest
 
       if @Bestan = 0 
       Begin
        Update  ghest  Set    FlagTypeAghsat=0  From deleted  Where ghest.Autoid= deleted.Autoid
      End
      if @Bestan <>0 
       Begin
            Update  ghest  Set    FlagTypeAghsat=1  From Inserted  Where ghest.autoid=inserted.Autoid
      End

      SELECT      @Nu_Ghest= HeadGh.Id_Ghest,@Guy_Code=HeadGh.Guy_Code, @Price=Bestan,@Nu_Ghest=AutoId,
                          @Aghsat_Nu=Aghsat_nu,@MonthGhest=MonthGhest,@userId=Inserted.USER_ID
       FROM         HeadGh INNER JOIN
                         Inserted  ON HeadGh.Id_Ghest =Inserted.Id_Ghest
      
      
      If Update (FlagTypeAghsat) 
      begin
        if  (@MonthGhest is null )
            Set @Note=LTRIM(Str(@Aghsat_Nu)) + '  از شخص  ' + @Guy_Code  
        else
           Set @Note=LTRIM(Str(@Aghsat_Nu)) +' ( ' +@MonthGhest+' كام ' +' ) ' + '  از شخص  ' + @Guy_Code 
        
          
          If @Price > 0  --and @Flag  is null 
              Exec   @Msg = Create_Sanad_Ghest @Msg , 41  ,  @Guy_Code ,@Price , 0  ,  @Note  ,  0  ,Null, @IdSanad, @Autoid,@userId
      end
    End



