[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Loop through tables in SQL Server and delete rows

Posted on 2011-09-26
5
Medium Priority
?
227 Views
Last Modified: 2012-06-27
Does anyone know how to loop through all tables in a SQL Server database and execute a DELETE FROM... on each table? I want to clean the database completely and thought there may be a way to utilize a loop for this. Thanks for any insight!
0
Comment
Question by:brianwells05
5 Comments
 
LVL 70

Assisted Solution

by:Éric Moreau
Éric Moreau earned 2000 total points
ID: 36600443
If you have foreign keys, your loop will fail. You better script your database, drop it, and recreate it from your script
0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 2000 total points
ID: 36600446
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 36600850
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 36671472
If you like to live dangerously you can try something like this:
exec sp_msforeachtable 'DELETE ?'

Just execute it as many times as necessary until you do not get any error message for foreign key violation.
0
 

Author Closing Comment

by:brianwells05
ID: 36719229
Several good answers. I agree with scripting the database, but I needed the delete option in my specific case. Thanks for the input!
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Integration Management Part 2
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…

834 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