CREATE TRIGGER [dbo].[TD_OverUnder] 
   ON  [dbo].[TmpDrugHavaleh] AFTER DELETE
AS 
BEGIN
  Declare @CodeOverUnder Smallint
  IF Not Exists(Select K_Code FRom TmpDrugHavaleh Where K_Code = '1' And Id_Havaleh in (Select Id_Havaleh From Deleted))
  Begin
    Select @CodeOverUnder = AutoId From Over_Under Where AutoId = 28
    Delete From Tmp_Over_Under_Factor_Drug Where Id_Havaleh in (Select Id_Havaleh From Deleted)
    And Code_Over_Under = @CodeOverUnder
  End
  Else IF Not Exists(Select K_Code From TmpDrugHavaleh Where K_Code = '2' And Id_Havaleh in (Select Id_Havaleh From Deleted))
  Begin
    Select @CodeOverUnder = AutoId From Over_Under Where AutoId = 28
    Delete From Tmp_Over_Under_Factor_Drug Where Id_Havaleh in (Select Id_Havaleh From Deleted)
    And Code_Over_Under = @CodeOverUnder
  End
  Else IF Not Exists(Select K_Code From TmpDrugHavaleh Where K_Code = '3' And Id_Havaleh in (Select Id_Havaleh From Deleted))
  Begin
    Select @CodeOverUnder = AutoId From Over_Under Where AutoId = 28
    Delete From Tmp_Over_Under_Factor_Drug Where Id_Havaleh in (Select Id_Havaleh From Deleted)
    And Code_Over_Under = @CodeOverUnder
  End
  
END
