Create TRIGGER [dbo].[Td_Sanad] ON [dbo].[Sanad] 
FOR DELETE 
AS

  Declare @NuHavaleh  BigInt
  Declare @NuVajeh  BigInt
  Declare @NuOverUnder  BigInt
  Declare @NuCooperative  BigInt
  Declare @IdSanad Bigint
  Declare @IdCheqe Bigint
  Declare @NuGhest  BigInt
  Declare @AutoGhest  Numeric(18,0)
  Declare @Guid_Cheqe uniqueidentifier
  Declare @PreGuid_Cheqe uniqueidentifier
  Declare @Guid_Sanad uniqueidentifier

  Declare Cursor_DeleteSanad Cursor Local For 
  Select Nu_Havaleh , Nu_Vajeh, Nu_Over_Under ,Guid_Sanad ,Nu_Ghest, Id_Sanad, Auto_Ghest, Nu_Cooperative From Deleted 

  Open Cursor_DeleteSanad
  Fetch Next From Cursor_DeleteSanad Into @NuHavaleh , @NuVajeh ,@NuOverUnder , @Guid_Sanad ,@NuGhest ,@IdSanad, @AutoGhest, @NuCooperative

  While @@FETCH_STATUS = 0     
  Begin
    IF (@NuHavaleh Is Null) And  (@NuOverUnder Is Null) And (@NuVajeh Is Not Null)  And (@NuGhest Is Null)
    Begin
      Select @Guid_Cheqe = Guid_Cheqe From Acc_Cheqe_Link Where Guid_Sanad = @Guid_Sanad
      Select @PreGuid_Cheqe = PreGuid_Cheqe, @IdCheqe = Id_Cheqe From Cheqe Where Guid_Cheqe = @Guid_Cheqe
      Delete From Cheqe Where Guid_Cheqe = @Guid_Cheqe
      Delete From Acc_Cheqe_Link  Where Guid_Cheqe = @Guid_Cheqe
      IF (Select Count(Cheqe.Id_Cheqe) From Cheqe Inner Join HeadC 
                             On (HeadC.Id_Cheqe = Cheqe.Id_Cheqe)
                             Where Cheqe.Id_Cheqe = @IdCheqe) = 0
           Delete From HeadC Where Id_Cheqe = @IdCheqe
      Update Cheqe Set Ch_Pass_New = Ch_Pass, Ch_Desc = ''  Where Guid_Cheqe =  @PreGuid_Cheqe
    End
    Else IF (@NuHavaleh  is not null Or @NuHavaleh =0)  and (@NuVajeh Is Null) And (@NuGhest Is Not Null Or @AutoGhest is Not Null)
    Begin
      IF (@NuGhest Is Not Null And @AutoGhest Is Null)
      Begin
        Delete Sanad  From Sanad Inner Join Headgh on HeadGh.Id_Ghest = Sanad.Nu_Ghest
        Where T_Bestan = 0 And Sanad.Id_Sanad = @IdSanad And Nu_Ghest=@NuGhest
        Delete from HeadGh where (id_ghest=@NuGhest) And T_Bestan = 0
      End
      Else IF (@NuGhest Is Null And @AutoGhest Is Not Null)
      begin
        Delete  From Sanad where Auto_Ghest= @AutoGhest And Id_Sanad = @IdSanad
        Update Ghest Set FlagTypeAghsat = '0' , Bestan = 0, Date_Dr = Null  Where Autoid = @AutoGhest
      End
    End 
    Fetch Next From Cursor_DeleteSanad Into @NuHavaleh , @NuVajeh ,@NuOverUnder , @Guid_Sanad ,@NuGhest ,@IdSanad, @AutoGhest,@NuCooperative
  End --While @@FETCH_STATUS = 0  

  CLOSE  Cursor_DeleteSanad
  DEALLOCATE  Cursor_DeleteSanad
