Loop through tables in SQL Server and delete rows

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!
brianwells05Asked:
Who is Participating?
 
Éric MoreauConnect With a Mentor Senior .Net ConsultantCommented:
If you have foreign keys, your loop will fail. You better script your database, drop it, and recreate it from your script
0
 
Kevin CrossChief Technology OfficerCommented:
0
 
Anthony PerkinsCommented:
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
 
brianwells05Author Commented:
Several good answers. I agree with scripting the database, but I needed the delete option in my specific case. Thanks for the input!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.