I would like to add some logic to the transaction below that would check the number of records inserted in the first table and deleted in the second one. These quantities should be the same and a comparison of them should evaluate as true. This should also rollback the transaction if the comparison doesn't evaluate as true because the record counts don't match. It's very important that same number of the records are inserted as are deleted so I thought this comparison would be good mechanism to ensure this. The count variables are intended for this.
DECLARE @PurgeDate AS VARCHAR(20) DECLARE @ArchiveInserts AS VARCHAR(30) DECLARE @GLTRdeletes AS VARCHAR(30) DECLARE @ArchiveInsertCount AS INT DECLARE @GLTRdeletesCount AS INT SET @PurgeDate = '04/04/2010' BEGIN TRAN GLTRpurge BEGIN TRY ---------------------------------------------------------------------------- -- Archive the records to be purged ---------------------------------------------------------------------------- SELECT COUNT(*) AS 'Archive Inserts' FROM GLTR WHERE PostDate <= @PurgeDate AND gltrInterfaceDate IS NOT NULL INSERT INTO GLTR_ARCHIVE SELECT * FROM GLTR WHERE PostDate <= @PurgeDate AND gltrInterfaceDate IS NOT NULL ORDER BY PostDate, ID --------------------------------------------------------------------------- -- Purge the original records to be archived ---------------------------------------------------------------------------- SELECT COUNT(*) AS 'GLTR Deletes' FROM GLTR WHERE PostDate <= @PurgeDate AND gltrInterfaceDate IS NOT NULL DELETE FROM GLTR WHERE ID IN (SELECT ID FROM GLTR WHERE PostDate <= @PurgeDate AND gltrInterfaceDate IS NOT NULL) COMMIT GLTRpurge END TRY BEGIN CATCH ROLLBACK GLTRpurge SELECT 'The transaction was rolled back' END CATCH
What is the best way to do this?