We help IT Professionals succeed at work.

SQL Deletion query loop

Medium Priority
376 Views
Last Modified: 2012-06-22
We have a database which uses SQL 2008. This application generates about 50,000 log files per day (each a row on the table) and I just found out that it hasn't been cleaned out in months. I want to create a query which will delete rows in the table in groups of 1000, then pause for a moment (to allow other proccesses CPU time, I don't want to choke the server) and then begin again. I have the basic deletion part but I can't seem to figure out how to make it loop. Here is what I have

set rowcount 1000
delete from <table> where LogDate <=getdate()-1
waitfor delay '00:00:01'
Comment
Watch Question

Ephraim WangoyaSoftware Engineer
CERTIFIED EXPERT

Commented:

try this


while exists(select count(1) from <table>)
begin
  set rowcount 1000
  delete from <table> where LogDate <=getdate()-1
  waitfor delay '00:00:01'
end

Open in new window

Ephraim WangoyaSoftware Engineer
CERTIFIED EXPERT

Commented:
modify to
while exists(select count(1) from <table> where LogDate <=getdate()-1)
begin
  set rowcount 1000
  delete from <table> where LogDate <=getdate()-1
  waitfor delay '00:00:01'
end

Open in new window

Author

Commented:
That did it, I forgot the while statement :)

Any way to make it display a simple "1,000 rows deleted" per cycle?
Software Engineer
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks for the quick reply!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.