I have this SQL:
```
-- =============================================
-- Temporary Stored Procedure: 
--  Archive Property by AssetId (Rules Compliant)
-- Description: 
--  Archives a property and its associated records following specific business rules
--  Transaction management is handled by the calling routine (not within this SP)
-- Parameters: 
--   @AssetId - The Asset ID of the property to archive
-- Notes:
--  This procedure is designed to be used in a batch processing context and
--  should be removed from the system, once used.
--  Transactions are managed by the calling routine to avoid INSERT-EXEC conflicts.
-- =============================================

CREATE OR ALTER PROCEDURE [dbo].[tmp_usp_ArchivePropertyByAssetId]
    @AssetId INT
AS
BEGIN
    SET NOCOUNT ON;
	SET XACT_ABORT ON;
    
    -- =============================================
    -- VARIABLES - DO NOT MODIFY
    -- =============================================
    DECLARE @RunId UNIQUEIDENTIFIER = NEWID();
    DECLARE @PropertyEntityTypeId INT;
    DECLARE @RisksEntityTypeId INT;
    DECLARE @AssessmentsEntityTypeId INT;
    DECLARE @DocumentsEntityTypeId INT;
    DECLARE @TasksEntityTypeId INT;
    DECLARE @IncidentsEntityTypeId INT;
    DECLARE @DateTimeNow DATETIME = GETDATE();
    DECLARE @SystemUserId INT;
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    DECLARE @PropertyReference NVARCHAR(255);

    -- Table variables to capture IDs before any state changes
    DECLARE @RiskIds TABLE (
        RiskId INT,
        AssociatedAssetId INT,
        AssociatedAssessmentId INT
    );

    DECLARE @AssessmentIds TABLE (
        AssessmentId INT,
        AssociatedAssetId INT
    );

    DECLARE @DocumentIds TABLE (
        DocumentId INT,
        AssociatedAssetId INT
    );

    DECLARE @TaskIds TABLE (
        TaskId INT,
        AssociatedAssetId INT
    );

    DECLARE @IncidentIds TABLE (
        IncidentId INT,
        AssociatedAssetId INT
    );

    DECLARE @AssetIds TABLE (
        AssetId INT,
        PropertyReference NVARCHAR(255)
    );

    -- Counters for reporting
    DECLARE @RisksArchived INT = 0;
    DECLARE @AssessmentsArchived INT = 0;
    DECLARE @DocumentsArchived INT = 0;
    DECLARE @TasksArchived INT = 0;
    DECLARE @IncidentsArchived INT = 0;
    DECLARE @AssetArchived INT = 0;

    -- Return values
    DECLARE @ReturnCode INT = 0;
    DECLARE @ReturnMessage NVARCHAR(500) = 'Success';

    BEGIN TRY
		-- =============================================
		-- INITIALIZATION AND VALIDATION
		-- =============================================
    
		PRINT '============================================';
		PRINT 'PROPERTY ARCHIVE PROCESS (RULES COMPLIANT)';
		PRINT '============================================';
		PRINT 'Run ID: ' + CAST(@RunId AS NVARCHAR(36));
		PRINT 'Asset ID: ' + CAST(@AssetId AS NVARCHAR(10));
		PRINT 'Started at: ' + CONVERT(NVARCHAR(20), @DateTimeNow, 120);
		PRINT '';
		-- Note: Transaction management is handled by the calling routine
		-- This procedure focuses purely on the archiving business logic
		-- Get the Property Entity Type ID
		SELECT @PropertyEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'AssetsProperties';

		IF @PropertyEntityTypeId IS NULL
		BEGIN
			RAISERROR('Entity type "AssetsProperties" not found', 16, 1);
			RETURN;
		END

		PRINT 'Property Entity Type ID: ' + CAST(@PropertyEntityTypeId AS NVARCHAR(10));

		-- Get other Entity Type IDs for logging
		SELECT @RisksEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'Risks';    SELECT @AssessmentsEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'Assessments';    
    
		SELECT @DocumentsEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'Documents';    
    
		SELECT @TasksEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'Tasks';

		SELECT @IncidentsEntityTypeId = Id
		FROM EntityTypes
		WHERE TypeName = 'Incidents';

		IF @RisksEntityTypeId IS NULL OR @AssessmentsEntityTypeId IS NULL OR @DocumentsEntityTypeId IS NULL OR @TasksEntityTypeId IS NULL OR @IncidentsEntityTypeId IS NULL
		BEGIN
			RAISERROR('Required entity types (Risks, Assessments, Documents, Tasks, Incidents) not found', 16, 1);
			RETURN;
		END

		PRINT 'Risks Entity Type ID: ' + CAST(@RisksEntityTypeId AS NVARCHAR(10));
		PRINT 'Assessments Entity Type ID: ' + CAST(@AssessmentsEntityTypeId AS NVARCHAR(10));
		PRINT 'Documents Entity Type ID: ' + CAST(@DocumentsEntityTypeId AS NVARCHAR(10));
		PRINT 'Tasks Entity Type ID: ' + CAST(@TasksEntityTypeId AS NVARCHAR(10));
		PRINT 'Incidents Entity Type ID: ' + CAST(@IncidentsEntityTypeId AS NVARCHAR(10));

		-- Get System User ID
		SELECT @SystemUserId = Id
		FROM Users 
		WHERE UserName = 'QuoodaSystem' AND IsDeleted = 0;

		IF @SystemUserId IS NULL
		BEGIN
			RAISERROR('System user "QuoodaSystem" not found', 16, 1);
			RETURN;
		END

		PRINT 'System User ID: ' + CAST(@SystemUserId AS NVARCHAR(10));

		-- =============================================
		-- PROPERTY VALIDATION
		-- =============================================
    
		PRINT '';
		PRINT 'Validating property...';

		-- Verify the asset exists and is a property
		IF NOT EXISTS (
			SELECT 1 
			FROM Assets A
			WHERE A.Id = @AssetId 
			  AND A.AssetTypeId = @PropertyEntityTypeId
		)
		BEGIN
			RAISERROR('Asset ID %d not found or is not a property', 16, 1, @AssetId);
			RETURN;
		END

		-- Get property details for reporting
		SELECT @PropertyReference = ISNULL(DisplayName, 'N/A')
		FROM Assets 
		WHERE Id = @AssetId;    
		PRINT 'Property Reference: ' + @PropertyReference;

		-- Check if already archived
		IF EXISTS (SELECT 1 FROM Assets WHERE Id = @AssetId AND IsArchived = 1)
		BEGIN
			PRINT 'WARNING: Property is already archived';
		END

		-- =============================================
		-- PHASE 1: DATA COLLECTION - Capture all IDs before any changes
		-- =============================================
    
		PRINT '';
		PRINT '============================================';
		PRINT 'PHASE 1: COLLECTING RECORD IDs TO PROCESS';
		PRINT '============================================';

		-- Collect all risk IDs that need archiving
		INSERT INTO @RiskIds (RiskId, AssociatedAssetId, AssociatedAssessmentId)
		SELECT DISTINCT R.Id, R.AssociatedAssetId, R.AssociatedAssessmentId
		FROM Risks R
		WHERE R.AssociatedAssetId = @AssetId
		  AND R.IsArchived = 0
		  AND R.IsDeleted = 0;

		DECLARE @RiskCount INT = @@ROWCOUNT;
		PRINT 'Risks identified for archiving: ' + CAST(@RiskCount AS NVARCHAR(10));

		SELECT COUNT(*) [COUNT IN VW_RISKS BEFORE ARCHIVE]
		FROM vw_Risks t1
		JOIN @RiskIds t2 on t2.RiskId = t1.Id;

		SELECT COUNT(*) [COUNT IN RISKSMATERIALISEDVIEW BEFORE ARCHIVE]
		FROM RisksMaterialisedView t1
		JOIN @RiskIds t2 on t2.RiskId = t1.Id;

		-- Collect all assessment IDs that need archiving  
		INSERT INTO @AssessmentIds (AssessmentId, AssociatedAssetId)
		SELECT DISTINCT R.AssociatedAssessmentId, R.AssociatedAssetId
		FROM Risks R
		WHERE R.AssociatedAssetId = @AssetId
		  AND R.IsArchived = 0
		  AND R.IsDeleted = 0;    

		DECLARE @AssessmentCount INT = @@ROWCOUNT;
		PRINT 'Assessments identified for archiving: ' + CAST(@AssessmentCount AS NVARCHAR(10));

		-- Collect all document IDs that need archiving from associations
		INSERT INTO @DocumentIds (DocumentId, AssociatedAssetId)
		SELECT DISTINCT VA.AssociatedEntityId, @AssetId
		FROM vw_Associations_All VA
		INNER JOIN EntityTypes ET ON ET.Id = VA.AssociatedEntityTypeId
		WHERE VA.EntityId = @AssetId 
		  AND VA.EntityTypeId = @PropertyEntityTypeId
		  AND ET.TypeName = 'Documents'
		  AND VA.AssociatedEntityId IS NOT NULL;    
      
		DECLARE @DocumentCount INT = @@ROWCOUNT;
		PRINT 'Documents identified for archiving: ' + CAST(@DocumentCount AS NVARCHAR(10));

		-- Collect all task IDs that need archiving from associations
		INSERT INTO @TaskIds (TaskId, AssociatedAssetId)
		SELECT DISTINCT VA.AssociatedEntityId, @AssetId
		FROM vw_Associations_All VA
		INNER JOIN EntityTypes ET ON ET.Id = VA.AssociatedEntityTypeId
		WHERE VA.EntityId = @AssetId 
		  AND VA.EntityTypeId = @PropertyEntityTypeId
		  AND ET.TypeName = 'Tasks'
		  AND VA.AssociatedEntityId IS NOT NULL;    
      
		DECLARE @TaskCount INT = @@ROWCOUNT;
		PRINT 'Tasks identified for archiving: ' + CAST(@TaskCount AS NVARCHAR(10));

		-- Collect all incident IDs that need archiving from associations
		INSERT INTO @IncidentIds (IncidentId, AssociatedAssetId)
		SELECT DISTINCT VA.AssociatedEntityId, @AssetId
		FROM vw_Associations_All VA
		INNER JOIN EntityTypes ET ON ET.Id = VA.AssociatedEntityTypeId
		WHERE VA.EntityId = @AssetId 
		  AND VA.EntityTypeId = @PropertyEntityTypeId
		  AND ET.TypeName = 'Incidents'
		  AND VA.AssociatedEntityId IS NOT NULL;

		DECLARE @IncidentCount INT = @@ROWCOUNT;
		PRINT 'Incidents identified for archiving: ' + CAST(@IncidentCount AS NVARCHAR(10));

		-- Collect the asset ID
		INSERT INTO @AssetIds (AssetId, PropertyReference)
		SELECT A.Id, ISNULL(A.DisplayName, 'N/A')
		FROM Assets A
		WHERE A.Id = @AssetId;

		DECLARE @AssetCount INT = @@ROWCOUNT;
		PRINT 'Asset identified for archiving: ' + CAST(@AssetCount AS NVARCHAR(10));

		-- Count entity associations (these will NOT be archived per rules)
		DECLARE @EntityAssociationCount INT = (
			SELECT COUNT(*)
			FROM vw_Associations_All EA
			WHERE EA.EntityId = @AssetId AND EA.EntityTypeId = @PropertyEntityTypeId
		);

		PRINT 'Entity associations (will remain unchanged): ' + CAST(@EntityAssociationCount AS NVARCHAR(10));

		-- Show detailed breakdown of what will be processed
		IF @RiskCount > 0
		BEGIN
			SELECT R1.RiskId [Risk IDs to be archived:], R1.AssociatedAssetId, R1.AssociatedAssessmentId, R2.IsDeleted, R2.IsArchived 
			FROM @RiskIds R1
			JOIN Risks R2 ON R1.RiskId = R2.Id
			ORDER BY RiskId;
		END    
	
		IF @AssessmentCount > 0
		BEGIN
			SELECT A1.AssessmentId [Assessment IDs to be archived:], A1.AssociatedAssetId, A2.IsDeleted, A2.IsArchived 
			FROM @AssessmentIds A1
			JOIN Assessments A2 ON A1.AssessmentId = A2.Id
			ORDER BY AssessmentId;
		END    
    
		IF @DocumentCount > 0
		BEGIN
			SELECT D1.DocumentId [Document IDs to be archived:], D1.AssociatedAssetId, D2.IsDeleted, D2.IsArchived 
			FROM @DocumentIds D1
			JOIN Documents D2 ON D1.DocumentId = D2.Id
			ORDER BY DocumentId;
		END    
    
		IF @TaskCount > 0
		BEGIN
			SELECT T1.TaskId [Task IDs to be archived:], T1.AssociatedAssetId, T2.IsDeleted, T2.IsArchived 
			FROM @TaskIds T1
			JOIN Tasks T2 ON T1.TaskId = T2.Id
			ORDER BY TaskId;
		END

		IF @IncidentCount > 0
		BEGIN
			SELECT I1.IncidentId [Incident IDs to be archived:], I1.AssociatedAssetId, I2.IsDeleted, I2.IsArchived 
			FROM @IncidentIds I1
			JOIN Incidents I2 ON I1.IncidentId = I2.Id
			ORDER BY IncidentId;
		END

		IF @AssetCount > 0
		BEGIN
			SELECT A1.AssetId [Asset ID to be archived:], A1.PropertyReference, A2.AssetTypeId, A2.IsDeleted, A2.IsArchived 
			FROM @AssetIds A1
			JOIN Assets A2 ON A1.AssetId = A2.Id;
		END

		-- =============================================
		-- PHASE 2: PROCESSING - Archive using captured IDs
		-- =============================================
    
		PRINT '';
		PRINT '============================================';
		PRINT 'PHASE 2: PROCESSING RECORDS FOR ARCHIVING';
		PRINT '============================================';

		-- =============================================
		-- ARCHIVE RISKS (Rule: Mark as archived, keep association columns unchanged)
		-- =============================================
    
		IF @RiskCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving risks using captured IDs...';        
			UPDATE R
			SET IsArchived = 1,
				DateUpdated = @DateTimeNow,
				UpdatedBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@RisksEntityTypeId AS EntityTypeId,
				inserted.AssociatedAssetId AS AssociatedEntityId,
				@PropertyEntityTypeId AS AssociatedEntityTypeId,
				deleted.UpdatedBy AS PreviousUpdatedBy,
				deleted.DateUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Risks R
			INNER JOIN @RiskIds RI ON R.Id = RI.RiskId
			-- Double-check current state
			WHERE R.IsArchived = 0  
			  AND R.IsDeleted = 0;

			SET @RisksArchived = @@ROWCOUNT;
			PRINT 'Risks archived: ' + CAST(@RisksArchived AS NVARCHAR(10));
        
			-- Verify association columns were preserved
			PRINT 'Verifying risk association columns were preserved...';
			SELECT 'Verification' AS CheckType, 
				   R.Id, 
				   R.AssociatedAssetId, 
				   R.AssociatedAssessmentId,
				   R.IsArchived
			FROM Risks R
			INNER JOIN @RiskIds RI ON R.Id = RI.RiskId;
		END

		-- =============================================
		-- ARCHIVE ASSESSMENTS (Rule: Mark as archived)
		-- =============================================
    
		IF @AssessmentCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving assessments using captured IDs...';        
		
			UPDATE A
			SET IsArchived = 1,
				DateUpdated = @DateTimeNow,
				UpdatedBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@AssessmentsEntityTypeId AS EntityTypeId,
				AI.AssociatedAssetId AS AssociatedEntityId,
				@PropertyEntityTypeId AS AssociatedEntityTypeId,
				deleted.UpdatedBy AS PreviousUpdatedBy,
				deleted.DateUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Assessments A
			INNER JOIN @AssessmentIds AI ON A.Id = AI.AssessmentId
			-- Double-check current state
			WHERE A.IsArchived = 0  
			  AND A.IsDeleted = 0;        
		
			SET @AssessmentsArchived = @@ROWCOUNT;
			PRINT 'Assessments archived: ' + CAST(@AssessmentsArchived AS NVARCHAR(10));
		END

		-- =============================================
		-- ARCHIVE DOCUMENTS (Rule: Mark as archived)
		-- =============================================
    
		IF @DocumentCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving documents using captured IDs...';
        
			UPDATE D
			SET IsArchived = 1,
				DateUpdated = @DateTimeNow,
				UpdatedBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@DocumentsEntityTypeId AS EntityTypeId,
				DI.AssociatedAssetId AS AssociatedEntityId,
				@PropertyEntityTypeId AS AssociatedEntityTypeId,
				deleted.UpdatedBy AS PreviousUpdatedBy,
				deleted.DateUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Documents D
			INNER JOIN @DocumentIds DI ON D.Id = DI.DocumentId
			-- Double-check current state
			WHERE D.IsArchived = 0  
			  AND D.IsDeleted = 0;        
        
			SET @DocumentsArchived = @@ROWCOUNT;
			PRINT 'Documents archived: ' + CAST(@DocumentsArchived AS NVARCHAR(10));
		END

		-- =============================================
		-- ARCHIVE TASKS (Rule: Mark as archived)
		-- =============================================
    
		IF @TaskCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving tasks using captured IDs...';
        
			UPDATE T
			SET IsArchived = 1,
				LastUpdated = @DateTimeNow,
				LastUpdateBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@TasksEntityTypeId AS EntityTypeId,
				TI.AssociatedAssetId AS AssociatedEntityId,
				@PropertyEntityTypeId AS AssociatedEntityTypeId,
				deleted.LastUpdateBy AS PreviousUpdatedBy,
				deleted.LastUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Tasks T
			INNER JOIN @TaskIds TI ON T.Id = TI.TaskId
			-- Double-check current state
			WHERE T.IsArchived = 0  
			  AND T.IsDeleted = 0;        
          
			SET @TasksArchived = @@ROWCOUNT;
			PRINT 'Tasks archived: ' + CAST(@TasksArchived AS NVARCHAR(10));
		END

		-- =============================================
		-- ARCHIVE INCIDENTS (Rule: Mark as archived)
		-- =============================================
    
		IF @IncidentCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving incidents using captured IDs...';
        
			UPDATE I
			SET IsArchived = 1,
				DateUpdated = @DateTimeNow,
				UpdatedBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@IncidentsEntityTypeId AS EntityTypeId,
				II.AssociatedAssetId AS AssociatedEntityId,
				@PropertyEntityTypeId AS AssociatedEntityTypeId,
				deleted.UpdatedBy AS PreviousUpdatedBy,
				deleted.DateUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Incidents I
			INNER JOIN @IncidentIds II ON I.Id = II.IncidentId
			-- Double-check current state
			WHERE I.IsArchived = 0  
			  AND I.IsDeleted = 0;

			SET @IncidentsArchived = @@ROWCOUNT;
			PRINT 'Incidents archived: ' + CAST(@IncidentsArchived AS NVARCHAR(10));
		END

		-- =============================================
		-- ARCHIVE ASSET (Rule: Mark as archived)
		-- =============================================
    
		IF @AssetCount > 0
		BEGIN
			PRINT '';
			PRINT 'Archiving property asset using captured ID...';        
			UPDATE A
			SET IsArchived = 1,
				DateUpdated = @DateTimeNow,
				UpdatedBy = @SystemUserId
			OUTPUT 
				@RunId AS RunId,
				@DateTimeNow AS RunDate,
				inserted.Id AS EntityId,
				@PropertyEntityTypeId AS EntityTypeId,
				NULL AS AssociatedEntityId,
				NULL AS AssociatedEntityTypeId,
				deleted.UpdatedBy AS PreviousUpdatedBy,
				deleted.DateUpdated AS PreviousUpdatedDate
			INTO Admin_ArchivedRecords (
				RunId, RunDate, EntityId, EntityTypeId, 
				AssociatedEntityId, AssociatedEntityTypeId, PreviousUpdatedBy, PreviousUpdatedDate
			)
			FROM Assets A
			INNER JOIN @AssetIds AI ON A.Id = AI.AssetId
			-- Double-check current state
			WHERE A.IsArchived = 0;  

			SET @AssetArchived = @@ROWCOUNT;
			PRINT 'Asset archived: ' + CAST(@AssetArchived AS NVARCHAR(10));
		END

		-- ===================================================================
		-- ENTITY ASSOCIATIONS (Rule: DO NOT archive/delete - leave unchanged)
		-- ===================================================================
    
		PRINT '';
		PRINT 'Entity associations status (per rules - these remain unchanged):';
		PRINT 'Total entity associations: ' + CAST(@EntityAssociationCount AS NVARCHAR(10));
		PRINT 'Action taken: NONE (per business rules)';

		-- =============================================
		-- FINAL REPORTING AND TRANSACTION HANDLING
		-- =============================================
    
		PRINT '';
		PRINT '============================================';
		PRINT 'ARCHIVE PROCESS SUMMARY';
		PRINT '============================================';
		PRINT 'Property ID: ' + CAST(@AssetId AS NVARCHAR(10));    
		PRINT 'Property Reference: ' + @PropertyReference;      
		PRINT 'Risks archived: ' + CAST(@RisksArchived AS NVARCHAR(10));
		PRINT 'Assessments archived: ' + CAST(@AssessmentsArchived AS NVARCHAR(10));
		PRINT 'Documents archived: ' + CAST(@DocumentsArchived AS NVARCHAR(10));
		PRINT 'Tasks archived: ' + CAST(@TasksArchived AS NVARCHAR(10));
		PRINT 'Incidents archived: ' + CAST(@IncidentsArchived AS NVARCHAR(10));
		PRINT 'Asset archived: ' + CAST(@AssetArchived AS NVARCHAR(10));
		PRINT 'Entity associations left unchanged: ' + CAST(@EntityAssociationCount AS NVARCHAR(10));

		DECLARE @TotalArchived INT = @RisksArchived + @AssessmentsArchived + @DocumentsArchived + @TasksArchived + @IncidentsArchived + @AssetArchived;
		PRINT 'Total records archived: ' + CAST(@TotalArchived AS NVARCHAR(10));    -- Show archived records if not dry run

		PRINT '';
		PRINT 'Archived records logged:';
		SELECT 
			AR.Id,
			ET.TypeName AS EntityType,
			AR.EntityId,
			AR.RunDate,
			AET.TypeName AS AssociatedEntityType,
			AR.AssociatedEntityId
		FROM Admin_ArchivedRecords AR
		LEFT JOIN EntityTypes ET ON ET.Id = AR.EntityTypeId
		LEFT JOIN EntityTypes AET ON AET.Id = AR.AssociatedEntityTypeId
		WHERE AR.RunId = @RunId
		ORDER BY ET.TypeName, AR.EntityId;

		SELECT COUNT(*) [COUNT IN VW_RISKS AFTER ARCHIVE]
		FROM vw_Risks t1
		JOIN @RiskIds t2 on t2.RiskId = t1.Id;

		SELECT COUNT(*) [COUNT IN RISKSMATERIALISEDVIEW AFTER ARCHIVE]
		FROM RisksMaterialisedView t1
		JOIN @RiskIds t2 on t2.RiskId = t1.Id;
		-- Transaction handling is managed by the calling routine
		PRINT '';
		PRINT 'Process completed at: ' + CONVERT(NVARCHAR(20), GETDATE(), 120);
		PRINT 'Run ID for reference: ' + CAST(@RunId AS NVARCHAR(36));

        
        -- Return success information
        SELECT 
            @ReturnCode AS ReturnCode,
            @ReturnMessage AS ReturnMessage,
            @RunId AS RunId,
            @AssetId AS AssetId,
            @PropertyReference AS PropertyReference,
            @RisksArchived AS RisksArchived,
            @AssessmentsArchived AS AssessmentsArchived,
            @DocumentsArchived AS DocumentsArchived,
            @TasksArchived AS TasksArchived,
            @IncidentsArchived AS IncidentsArchived,
            @AssetArchived AS AssetArchived,
            (@RisksArchived + @AssessmentsArchived + @DocumentsArchived + @TasksArchived + @IncidentsArchived + @AssetArchived) AS TotalArchived;

    END TRY    BEGIN CATCH
        SET @ReturnCode = -1;
        SET @ReturnMessage = ERROR_MESSAGE();
        
        -- Transaction rollback is handled by the calling routine

        -- Return error information
        SELECT 
            @ReturnCode AS ReturnCode,
            @ReturnMessage AS ReturnMessage,
            @RunId AS RunId,
            @AssetId AS AssetId,
            NULL AS PropertyReference,
            0 AS RisksArchived,
            0 AS AssessmentsArchived,
            0 AS DocumentsArchived,
            0 AS TasksArchived,
            0 AS IncidentsArchived,
            0 AS AssetArchived,
            0 AS TotalArchived;
    END CATCH
END;
GO

-- =============================================
-- BATCH EXECUTION SCRIPT FOR R&R ORGANIZATION
-- =============================================
SET NOCOUNT ON;

DECLARE @OrgId INT;
DECLARE @OrgName NVARCHAR(50);

SELECT Top 1 @OrgId = Id, @OrgName = OrganizationName FROM Organizations WHERE IsDeleted = 0

-- First, verify we have a valid organization
IF NOT EXISTS (SELECT 1 FROM Organizations WHERE Id = @OrgId AND OrganizationName = @OrgName)
BEGIN
    RAISERROR('Organization Id and Name could not be verified.', 16, 1);
    RETURN;
END

PRINT '========================================================================================';
PRINT @OrgName + ' PROPERTY ARCHIVE BATCH PROCESS';
PRINT '========================================================================================';
PRINT 'Organization verified: ' + @OrgName + ' (ID: ' + CAST(@OrgId AS VARCHAR(6)) + ')';
PRINT 'Started at: ' + CONVERT(NVARCHAR(20), GETDATE(), 120);
PRINT '';

-- Configuration
-- Set to 0 to commit changes, 1 for test run
DECLARE @IsDryRun BIT = 1; 

-- List of Asset IDs to archive
DECLARE @AssetIds TABLE (
    AssetId INT NOT NULL,
    ProcessOrder INT IDENTITY(1,1),
    Processed BIT NOT NULL DEFAULT 0,
    Success BIT NOT NULL DEFAULT 0,
    ErrorMessage NVARCHAR(500) NOT NULL DEFAULT N'NOT RUN'
);

-- Insert the 53 Asset IDs
INSERT INTO @AssetIds (AssetId)
SELECT A2.Id [AssetId]
FROM RISKS R1 
JOIN ASSETS A2 ON A2.Id = R1.AssociatedAssetId AND (A2.IsDeleted=1 OR A2.IsArchived=1) 
WHERE R1.IsDeleted=0 AND R1.IsArchived=0
GROUP BY A2.Id, A2.AssetTypeId, A2.IsDeleted, A2.IsArchived
HAVING COUNT(*) > 0
ORDER BY AssetId

-- Batch processing variables
DECLARE @CurrentAssetId INT;
DECLARE @ProcessOrder INT;
DECLARE @TotalAssets INT;
DECLARE @ProcessedCount INT = 0;
DECLARE @SuccessCount INT = 0;
DECLARE @ErrorCount INT = 0;

SELECT @TotalAssets = COUNT(*) FROM @AssetIds;

PRINT 'Total properties to archive: ' + CAST(@TotalAssets AS NVARCHAR(10));
PRINT 'Dry Run Mode: ' + CASE WHEN @IsDryRun = 1 THEN 'YES (No changes will be committed)' ELSE 'NO (Changes will be committed)' END;
PRINT '';

-- Process each Asset ID
DECLARE asset_cursor CURSOR FOR
SELECT AssetId, ProcessOrder
FROM @AssetIds
ORDER BY ProcessOrder;

OPEN asset_cursor;
FETCH NEXT FROM asset_cursor INTO @CurrentAssetId, @ProcessOrder;

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '--------------------------------------------';
    PRINT 'Processing Asset ID: ' + CAST(@CurrentAssetId AS NVARCHAR(10)) + ' (' + CAST(@ProcessOrder AS NVARCHAR(10)) + ' of ' + CAST(@TotalAssets AS NVARCHAR(10)) + ')';
    PRINT '--------------------------------------------';
      BEGIN TRY
        -- Transaction management: Start transaction here (outside of SP)
        SET XACT_ABORT ON;
        BEGIN TRANSACTION ArchiveAssetTran;
        
        -- Execute the archive procedure for this Asset ID
        EXEC [dbo].[tmp_usp_ArchivePropertyByAssetId] @AssetId = @CurrentAssetId;

        -- Mark as successful
        UPDATE @AssetIds 
        SET Processed = 1, Success = 1, ErrorMessage = 'COMPLETE'
        WHERE AssetId = @CurrentAssetId;
        
        IF @IsDryRun = 1
        BEGIN
            PRINT 'DRY RUN: No transaction committed for Asset ID ' + CAST(@CurrentAssetId AS NVARCHAR(10));
			ROLLBACK TRANSACTION ArchiveAssetTran;
        END
		ELSE 
        BEGIN
            PRINT 'Transaction committed for Asset ID ' + CAST(@CurrentAssetId AS NVARCHAR(10));
			COMMIT TRANSACTION ArchiveAssetTran;
        END

		SET @SuccessCount = @SuccessCount + 1;
        
    END TRY    
	
	BEGIN CATCH
        DECLARE @ErrorMsg NVARCHAR(500) = ERROR_MESSAGE();
        
        -- Transaction management: Rollback if error and not dry run
        IF XACT_STATE() <> 0
        BEGIN
            ROLLBACK TRANSACTION ArchiveAssetTran;
            PRINT 'Transaction rolled back due to error for Asset ID ' + CAST(@CurrentAssetId AS NVARCHAR(10));
        END
        
        -- Mark as processed but failed
        UPDATE @AssetIds 
        SET Processed = 1, Success = 0, ErrorMessage = @ErrorMsg
        WHERE AssetId = @CurrentAssetId;
        
        SET @ErrorCount = @ErrorCount + 1;
        PRINT 'ERROR: Asset ID ' + CAST(@CurrentAssetId AS NVARCHAR(10)) + ' failed: ' + @ErrorMsg;
    END CATCH
    
    SET @ProcessedCount = @ProcessedCount + 1;
    PRINT '';
    
    FETCH NEXT FROM asset_cursor INTO @CurrentAssetId, @ProcessOrder;
END

CLOSE asset_cursor;
DEALLOCATE asset_cursor;

-- =============================================
-- FINAL SUMMARY AND CLEANUP
-- =============================================

PRINT '============================================';
PRINT 'BATCH PROCESS SUMMARY';
PRINT '============================================';
PRINT 'Total properties: ' + CAST(@TotalAssets AS NVARCHAR(10));
PRINT 'Total processed: ' + CAST(@ProcessedCount AS NVARCHAR(10));
PRINT 'Successfully processed: ' + CAST(@SuccessCount AS NVARCHAR(10));
PRINT 'Failed: ' + CAST(@ErrorCount AS NVARCHAR(10));
PRINT 'Completed at: ' + CONVERT(NVARCHAR(20), GETDATE(), 120);
PRINT '';

-- Show detailed results
PRINT 'DETAILED RESULTS:';
SELECT 
    AssetId,
    ProcessOrder,
    CASE WHEN Success = 1 THEN 'SUCCESS' ELSE 'FAILED' END AS Status,
    ErrorMessage
FROM @AssetIds
ORDER BY ProcessOrder;

-- Show summary by status
SELECT 
    CASE WHEN Success = 1 THEN 'SUCCESS' ELSE 'FAILED' END AS [SUMMARY BY STATUS:],
    COUNT(*) AS Count
FROM @AssetIds
GROUP BY Success;

-- Show any failures
IF @ErrorCount > 0
BEGIN
    SELECT AssetId [FAILED ASSETS DETAILS:], ErrorMessage
    FROM @AssetIds
    WHERE Success = 0
    ORDER BY ProcessOrder;
END

-- Drop the temporary stored procedure
PRINT '';
PRINT 'Cleaning up temporary stored procedure...';
DROP PROCEDURE IF EXISTS [dbo].[tmp_usp_ArchivePropertyByAssetId];
PRINT 'Temporary stored procedure [tmp_usp_ArchivePropertyByAssetId] has been dropped.';

PRINT '';
PRINT '============================================';
PRINT 'BATCH PROCESS COMPLETED';
PRINT '============================================';
```

I want to put that script into the following so it is run on every database.
```
USE MASTER;

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'
...
';

EXEC dbo.sp_ineachdb @command = @sql, @name_pattern = 'Quooda%', @print_dbname = 1;

````

Can you do that for me?