Solved

Loop through tables in SQL Server and delete rows

Posted on 2011-09-26
5
220 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 500 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 500 total points
ID: 36600446
0
 
LVL 59

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
T-SQL Default value in Select? 5 38
error in my cursor 5 41
Trouble with <> 2 21
SQL Server 2005 database messed up. Can it be fixed? 4 17
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

828 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