• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

Batch Delete Script

I am trying to build a script that will delete a fixed number of records at a time, such as 10,000, from a table based on the primary key.   The table name is Trans and the primary key column name is ID.  In a separate table named TransIDsToDelete, I have one column named TransID which contains the IDs of the records I would like to delete from the Trans table.  The TransIDs are listed from lowest to highest.  Most of the TransIDs in the TransIDsToDelete table increment by 1, but occasionally there may be a very sudden increase in the value for the TransID.  For example the value for TransID may be 1500 for the 100th row, but the value for row 101 is 23989.  I would also like to specify the total number of records I'd like to delete, and have the script iterate through until that number is reached, and then terminate.  Can someone provide me with an example that deletes the records from the Trans table in batches of say 10000?
1 Solution
lcohanDatabase AnalystCommented:
Here's one example:

create table ##DelRows (DelId int)
while (1=1)
      truncate table ##DelRows
      insert into ##DelRows(DelId) select top 10000 ResDemandId from ResourceDemand (NOLOCK) where Effort=0
      if @@rowcount = 0 break
      delete dbo.ResourceDemand
      from dbo.resourcedemand, ##DelRows
      where dbo.ResourceDemandId = ##DelRows.DelId
      if @@rowcount = 0 break
drop table ##DelRows

One more using ROWCOUNT


DECLARE @rc int
SET @rc=10000
WHILE @rc=10000
      DELETE top(10000) FROM TableName
            WHERE RowId IN (SELECT ID FROM RelatedTable)
      SELECT @rc=@@rowcount
QlemoBatchelor and DeveloperCommented:
The last example is too much. Either use SET ROWCOUNT or TOP, but in combination don't make sense.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now