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?
navajo26354Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lcohanDatabase AnalystCommented:
Here's one example:



create table ##DelRows (DelId int)
while (1=1)
begin
      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
end
drop table ##DelRows

One more using ROWCOUNT


SET ROWCOUNT 10000

DECLARE @rc int
SET @rc=10000
WHILE @rc=10000
BEGIN
      DELETE top(10000) FROM TableName
            WHERE RowId IN (SELECT ID FROM RelatedTable)
      SELECT @rc=@@rowcount
END
SET ROWCOUNT 0
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
The last example is too much. Either use SET ROWCOUNT or TOP, but in combination don't make sense.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.