Sample Header Ad - 728x90

Delete million of rows from parent and child tables in SQL Server

1 vote
1 answer
219 views
I have three tables: Records, ChildTable, and ParentTable. ChildTable and ParentTable both have RecordId as the foreign key. My aim is to delete all records older than 300 days from the Records table, along with corresponding entries from the other two tables. The Records table contains nearly a million records to be deleted, while ChildTable and ParentTable collectively hold around 3 million rows for all the RecordIds being deleted. I'm executing these deletions in batches of 4000 and would like to verify if the logic I'm employing is correct. Any assistance would be greatly appreciated. Thank you!
Declare @errorMessage	Varchar(1000)
Declare @counter		Int = 0
Declare @BatchSize		Int = 1000

Set NoCount On

WHILE (1=1)
BEGIN
	Begin Try
		Begin Tran

			/****** Get all the deletions from the records  ******/
			Select Top (@BatchSize) RecordId
			  Into #TempDeletions
			  From [dbo].[Records] With(NoLock)
			 Where LastDate  0
			Rollback Tran

		Select Error_Message()
	End Catch
END
Asked by lifeisajourney (751 rep)
Feb 12, 2024, 03:47 PM
Last activity: Jun 27, 2025, 03:06 AM