

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='TR' AND name='trig_FOLDER')
    DROP TRIGGER trig_FOLDER
/

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='TR' AND name='trig_PAGE')
    DROP TRIGGER trig_PAGE
/

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='TR' AND name='trig_FRAGMENT')
    DROP TRIGGER trig_FRAGMENT
/

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='TR' AND name='trig_FOLDER_MENU')
    DROP TRIGGER trig_FOLDER_MENU
/

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='TR' AND name='trig_PAGE_MENU')
    DROP TRIGGER trig_PAGE_MENU
/


CREATE TRIGGER trig_FOLDER
  ON FOLDER 
  INSTEAD OF DELETE 
  AS 
 
  SET NOCOUNT ON;

  WITH cte AS 
  ( SELECT FOLDER_ID, PARENT_ID 
    FROM DELETED 
    UNION ALL 
    SELECT c.FOLDER_ID, c.PARENT_ID
    FROM FOLDER AS c 
    INNER JOIN cte AS p 
    ON c.PARENT_ID = p.FOLDER_ID 
  ) 
  SELECT * 
  into #tmp
  FROM cte
  OPTION (MAXRECURSION 32767)
  
  DELETE FROM PAGE
    WHERE PARENT_ID IN (SELECT FOLDER_ID FROM #tmp);  

  DELETE FROM FOLDER_MENU
    WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM #tmp);  

  DELETE FROM FOLDER
    where FOLDER_ID IN (
      SELECT FOLDER_ID FROM #TMP)
 
  
  drop table #tmp
/

CREATE TRIGGER trig_FOLDER_MENU
  ON FOLDER_MENU
  INSTEAD OF DELETE 
  AS 

  SET NOCOUNT ON;

  WITH cte AS 
  ( SELECT MENU_ID, PARENT_ID 
    FROM DELETED 
    UNION ALL 
    SELECT c.MENU_ID, c.PARENT_ID
    FROM FOLDER_MENU AS c 
    INNER JOIN cte AS p 
    ON c.PARENT_ID = p.MENU_ID 
  ) 
  SELECT * 
  into #tmp
  FROM cte
  OPTION (MAXRECURSION 32767)

  DELETE FROM FOLDER_MENU
    WHERE MENU_ID IN(
      SELECT MENU_ID FROM #tmp)
  
  drop table #tmp
/

CREATE TRIGGER [trig_PAGE]
  ON PAGE
  INSTEAD OF DELETE 
  AS 
  
  SET NOCOUNT ON;
 
  DELETE FROM PAGE_MENU
    WHERE PAGE_ID IN (SELECT PAGE_ID FROM DELETED);  

  DELETE FROM FRAGMENT
    WHERE PAGE_ID IN (SELECT PAGE_ID FROM DELETED);  

  DELETE FROM PAGE
	WHERE PAGE_ID IN (SELECT PAGE_ID FROM DELETED);
/

CREATE TRIGGER trig_PAGE_MENU
  ON PAGE_MENU 
  INSTEAD OF DELETE 
  AS 
 
  SET NOCOUNT ON;

  WITH cte AS 
  ( SELECT MENU_ID, PARENT_ID 
    FROM DELETED 
    UNION ALL 
    SELECT c.MENU_ID, c.PARENT_ID
    FROM PAGE_MENU AS c 
    INNER JOIN cte AS p 
    ON c.PARENT_ID = p.MENU_ID 
  ) 
  SELECT * 
  into #tmp
  FROM cte
  OPTION (MAXRECURSION 32767)

  DELETE FROM PAGE_MENU 
    WHERE MENU_ID IN (
      SELECT MENU_ID FROM #tmp)
  
  drop table #tmp
/

CREATE TRIGGER trig_FRAGMENT
  ON FRAGMENT 
  INSTEAD OF DELETE 
  AS 
 
  SET NOCOUNT ON;

  WITH cte AS 
  ( SELECT FRAGMENT_ID, PARENT_ID 
    FROM DELETED 
    UNION ALL 
    SELECT c.FRAGMENT_ID, c.PARENT_ID
    FROM FRAGMENT AS c 
    INNER JOIN cte AS p 
    ON c.PARENT_ID = p.FRAGMENT_ID 
  ) 
  SELECT * 
  into #tmp
  FROM cte
  OPTION (MAXRECURSION 32767)

  DELETE FROM FRAGMENT
    WHERE FRAGMENT_ID IN
      (SELECT FRAGMENT_ID FROM #TMP)
  
  drop table #tmp
/
