Print ''
Print '========================================================================='
Print ' Delete all Object Data and All JobResults'
Print ' Autor        : J.Feuerstein'
Print ' L.Update.....: 14.10.2015 J.Fes'
Print '========================================================================='


use [#DB_N#]

Print 'Database: #DB_N#'
Print '-------------------------------------------------------------------------'

  If Exists (select Name  from sysobjects  where Name = "FK_ObjectGroupsRel_ObjectGroups" and type = "F")
  BEGIN
   Print '    |-> Remove FOREIGN KEY (1/2) "FK_ObjectGroupsRel_ObjectGroups" --'
   ALTER TABLE [dbo].[Objects_ObjectGroups_Rel_tbl] DROP CONSTRAINT [FK_ObjectGroupsRel_ObjectGroups]
  END

  If Exists (select Name  from sysobjects  where Name = "FK_ObjectGroupsRel_Objects" and type = "F")
  BEGIN
   Print '    |-> Remove FOREIGN KEY (2/2) "FK_ObjectGroupsRel_Objects" --'
   ALTER TABLE [dbo].[Objects_ObjectGroups_Rel_tbl] DROP CONSTRAINT [FK_ObjectGroupsRel_Objects]
  END

  Print '    |-> all Data from Table: JobControl_ObjectsProcessData_tbl'
  TRUNCATE TABLE [dbo].[JobControl_ObjectsProcessData_tbl]

  Print '    |-> all Data from Table: Objects_Ir_Rel_tbl'
  TRUNCATE TABLE [dbo].[Objects_Ir_Rel_tbl]

  Print '    |-> all Data from Table: Objects_ObjectGroups_Rel_tbl'
  TRUNCATE TABLE [dbo].[Objects_ObjectGroups_Rel_tbl]

  Print '    |-> all Data from Table: Objects_tbl'
  TRUNCATE TABLE [dbo].[Objects_tbl]

  -- see: ..\JobMgr_11_DataTable_Objects_ObjectGroups_Rel_tbl.sql
  If NOT Exists (select Name  from sysobjects  where Name = "FK_ObjectGroupsRel_ObjectGroups" and type = "F")
  BEGIN
    Print '    |-> Create FOREIGN KEY (1/2) "FK_ObjectGroupsRel_ObjectGroups" --'
    ALTER TABLE [dbo].[Objects_ObjectGroups_Rel_tbl]
    ADD CONSTRAINT [FK_ObjectGroupsRel_ObjectGroups] FOREIGN KEY ([ObjectGroupId])
    REFERENCES [dbo].[ObjectGroups_tbl] ([Id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
  END

  If NOT Exists (select Name  from sysobjects  where Name = "FK_ObjectGroupsRel_Objects" and type = "F")
  BEGIN
    Print '    |-> Create FOREIGN KEY (2/2) "FK_ObjectGroupsRel_Objects" --'
    ALTER TABLE [dbo].[Objects_ObjectGroups_Rel_tbl]
    ADD CONSTRAINT [FK_ObjectGroupsRel_Objects] FOREIGN KEY ([ObjectId])
    REFERENCES [dbo].[Objects_tbl] ([Id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
  END

  Print '    |-> cleanup count ObjectGroups_tbl'
  update ObjectGroups_tbl set ObjectReferenceCount_ITEM = 0
  update ObjectGroups_tbl set ObjectReferenceCount_IR = 0
  update ObjectGroups_tbl set ObjectReferenceCount_DS = 0


Print '========================================================================='
Print ' End of Script'
Print '========================================================================='
GO
