Solved

Executing a select statement in batches

Posted on 2012-04-12
3
193 Views
Last Modified: 2012-04-12
Hi,

I would like to take this statement:

delete from table where date <= '12/31/2000'

This coudl result in over 10,000,000 rows or more.

I want to do this in batches of 20,000 in a script. Any suggestions on the best way to do this?

Thanks,

Basil
0
Comment
Question by:basile
  • 2
3 Comments
 
LVL 39

Accepted Solution

by:
lcohan earned 500 total points
ID: 37839964
You should look at SET ROWCOUNT = xxx and use that to build your batch delete
http://msdn.microsoft.com/en-us/library/ms188774(SQL.105).aspx

smething like:

SET ROWCOUNT 2000
      DECLARE @rc int
      SET @rc=2000
      WHILE @rc=2000
BEGIN
      delete from orders with (rowlock) where chargestatus = 8
    SELECT @rc=@@rowcount
END
SET ROWCOUNT 0
0
 
LVL 39

Expert Comment

by:lcohan
ID: 37839976
Or to be more speciffic:


SET ROWCOUNT 20000
      DECLARE @rc int
      SET @rc=20000
      WHILE @rc=20000
BEGIN
     delete from table where date <= '12/31/2000'
     SELECT @rc=@@rowcount
END
SET ROWCOUNT 0

and m,ake sure you have a index on table.date column and you could include a

UPDATE STATISTICS table in above batch delete after each 1 000 000 rows for instance
0
 
LVL 1

Author Closing Comment

by:basile
ID: 37840010
Perfect!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now