Create TRIGGER [dbo].[TD_RepEkhtetam] ON [dbo].[RepEkhtetam] 
FOR DELETE 
AS

Declare @Count  smallint
Declare @Parent smallint

Declare CursorDelete Cursor For
Select  parent_code from deleted 
Open CursorDelete
Fetch Next From CursorDelete Into @parent
While @@Fetch_Status = 0 
Begin
  SELECT  @count = count (*)  FROM RepEkhtetam 
  left outer join RepEkhtetam RepEkhtetam_1 ON RepEkhtetam.AutoId = RepEkhtetam_1.Parent_Code
  WHERE     (RepEkhtetam.parent_Code = @parent)

  if (@count =0 )
    if Exists (Select * From RepEkhtetam Where Autoid =@parent )
      Update RepEkhtetam set Has_Child = 0 , Bedeh = 0 , Bestan = 0  where autoid = @parent
  Fetch Next From CursorDelete Into @parent
End       
Close CursorDelete
Deallocate CursorDelete
    
