BEGIN TRY
    -- ------------------------------------------
    -- DECLARE VARIABLES
    -- ------------------------------------------
    DECLARE @rowCount INT
    DECLARE @enableLog BIT

    -- ------------------------------------------
    -- CONFIGURABLE ATTRIBUTES
    -- ------------------------------------------
    SET @enableLog = 1 -- ENABLE LOGGING [DEFAULT : TRUE]

    IF (@enableLog = 1)
    BEGIN
        SELECT '[' + convert(varchar, getdate(), 121) + '] SAML IDP METADATA CLEANUP DATA RESTORATION STARTED .... !' AS 'INFO_LOG'
    END

    SELECT @rowCount = COUNT(1)  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN ('REG_RESOURCE');
    IF (@rowCount = 1)
    BEGIN
        BEGIN TRANSACTION;
        SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

        SET IDENTITY_INSERT REG_RESOURCE ON;
        INSERT INTO REG_RESOURCE (REG_PATH_ID, REG_NAME, REG_VERSION, REG_MEDIA_TYPE, REG_CREATOR, REG_CREATED_TIME,
         REG_LAST_UPDATOR, REG_LAST_UPDATED_TIME, REG_DESCRIPTION, REG_CONTENT_ID, REG_TENANT_ID, REG_UUID) SELECT
         A.REG_PATH_ID, A.REG_NAME, A.REG_VERSION, A.REG_MEDIA_TYPE, A.REG_CREATOR, A.REG_CREATED_TIME, A.REG_LAST_UPDATOR,
         A.REG_LAST_UPDATED_TIME, A.REG_DESCRIPTION, A.REG_CONTENT_ID, A.REG_TENANT_ID, A.REG_UUID FROM BAK_REG_RESOURCE A LEFT
         JOIN REG_RESOURCE B ON A.REG_VERSION = B.REG_VERSION AND A.REG_TENANT_ID = B.REG_TENANT_ID WHERE B.REG_VERSION IS NULL;
        SET @rowCount = @@ROWCOUNT;
        SET IDENTITY_INSERT REG_RESOURCE OFF;

        SET IDENTITY_INSERT REG_CONTENT ON;
        INSERT INTO REG_CONTENT (REG_CONTENT_ID, REG_CONTENT_DATA, REG_TENANT_ID) SELECT A.REG_CONTENT_ID,
         A.REG_CONTENT_DATA, A.REG_TENANT_ID FROM BAK_REG_CONTENT A LEFT JOIN REG_CONTENT B ON
         A.REG_CONTENT_ID = B.REG_CONTENT_ID WHERE B.REG_CONTENT_ID IS NULL;
        SET IDENTITY_INSERT REG_CONTENT OFF;
        IF (@enableLog = 1)
        BEGIN
            SELECT CONCAT('CLEANUP DATA RESTORATION COMPLETED ON REG_RESOURCE WITH ', @rowCount) AS 'INFO_LOG'
        END
        COMMIT TRANSACTION;
    END

    IF (@enableLog = 1)
    BEGIN
        SELECT  '[' + convert(varchar, getdate(), 121) + '] CLEANUP DATA RESTORATION COMPLETED .... !' AS 'INFO_LOG'
    END
END TRY
BEGIN CATCH

    IF (@enableLog = 1)
    BEGIN
        SELECT '[' + convert(varchar, getdate(), 121) + '] ERROR OCCURRED: ' + ERROR_MESSAGE() AS 'ERROR LOG'
    END

    ROLLBACK TRANSACTION
END CATCH
