USE [DocumedisLogs]
GO

/*
MDDOC-878

Purge of the table documedisLogs.dbo.Documedis_VaccinationCheck_LogData

Only records that are more than 7 months old and present as archived in [archivedRowsJournal]
will be purged.

Deletion is made in small batches to avoid locking.
Only 1 iteration is made, the job calling this procedure will handle the calls and be executed several times.
it will also handle the hours the deletion should run from / to
*/
CREATE OR ALTER PROCEDURE [purge_Documedis_VaccinationCheck_LogData] AS
BEGIN
    DECLARE @cutoff DATE = DATEADD(MONTH, -7, CURRENT_TIMESTAMP);
    DECLARE @batch INT = 5000;
    DECLARE @tbl_to_del TABLE (DocumedisVaccinationCheckLogData_PK BIGINT NOT NULL );
    
    BEGIN TRANSACTION

    -- region populate filter table
    INSERT INTO @tbl_to_del([DocumedisVaccinationCheckLogData_PK])
    SELECT TOP (@batch)
           [s].[DocumedisVaccinationCheckLogData_PK]
    FROM [dbo].[Documedis_VaccinationCheck_LogData] [s]
    WHERE [s].[LogDateTime] > @cutoff
      AND EXISTS(
        SELECT 1
        FROM [archivedRowsJournal] [a]
        WHERE [a].[tableName] = 'Documedis_VaccinationCheck_LogData'
          AND [a].[tableRowId] = [s].[DocumedisVaccinationCheckLogData_PK]
    );
    -- endregion

    -- region Documedis_VaccinationCheck_LogData
    DELETE [s]
    FROM @tbl_to_del d
        INNER JOIN [Documedis_VaccinationCheck_LogData] s ON [s].[DocumedisVaccinationCheckLogData_PK] = [d].[DocumedisVaccinationCheckLogData_PK];
    PRINT CONVERT(VARCHAR(20), CURRENT_TIMESTAMP, 114)+' - Deleted from Documedis_VaccinationCheck_LogData. '+REPLACE(REPLACE(CONVERT(VARCHAR(100), CONVERT(MONEY, @@rowcount), 1),',',''''),'.00','')+' row(s) affected.';
    -- endregion

    -- region archivedRowsJournal
    DELETE j
    FROM [archivedRowsJournal] j
        INNER JOIN @tbl_to_del d ON [j].[tableRowId] = [d].[DocumedisVaccinationCheckLogData_PK]
    WHERE [j].[tableName]='Documedis_VaccinationCheck_LogData';
    PRINT CONVERT(VARCHAR(20), CURRENT_TIMESTAMP, 114)+' - Deleted from archivedRowsJournal. '+REPLACE(REPLACE(CONVERT(VARCHAR(100), CONVERT(MONEY, @@rowcount), 1),',',''''),'.00','')+' row(s) affected.';
    -- endregion
        
    COMMIT TRANSACTION
END
