IF OBJECT_ID('[dbo].[MaintainHCIChangeTrackingHistory]') IS NOT NULL 
BEGIN 
	DROP PROCEDURE [dbo].[MaintainHCIChangeTrackingHistory];
END
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER ON 
GO
/*============================================================================= 

Description
----------------------
	OCTP-2459

	Cleans history data in HCIChangeTracking.
	Deletes all records older than 2 years in the following tables:
		* [OlpDirectoryChangeLog]
		* [OlpfactChangeLog]
		* [OlpfactValidatorChangeLog]

Where
----------------------
	On all TriaFact instances

Dependencies
----------------------
	Called by job [W030100 - Cleanup HCIChangeTracking]

Creation: 
	03.11.2022 / TSC

Modifications:

=============================================================================*/ 
CREATE PROCEDURE dbo.MaintainHCIChangeTrackingHistory
AS
BEGIN 
	SET NOCOUNT ON;

	DECLARE
		@deleted    INT
	   ,@batch_size INT  = 100000
	   ,@today      DATE = DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0);

	SET @deleted = 1;
	WHILE @deleted > 0 BEGIN
		DELETE TOP (@batch_size) cl
		FROM dbo.[OlpDirectoryChangeLog] cl
		WHERE cl.CreationDate < DATEADD(YEAR, -2, @today);

		SET @deleted = @@ROWCOUNT;
	END

	SET @deleted = 1;
	WHILE @deleted > 0 BEGIN
		DELETE TOP (@batch_size) cl
		FROM dbo.[OlpfactChangeLog] cl
		WHERE cl.CreationDate < DATEADD(YEAR, -2, @today);

		SET @deleted = @@ROWCOUNT;
	END

	SET @deleted = 1;
	WHILE @deleted > 0 BEGIN
		DELETE TOP (@batch_size) cl
		FROM dbo.[OlpfactValidatorChangeLog] cl
		WHERE cl.CreationDate < DATEADD(YEAR, -2, @today);

		SET @deleted = @@ROWCOUNT;
	END
END
