The Safe and Easy Way to Delete All Data in a SQL Server DB
Deleting all the data in a SQL Server database doesn't have to involve complex code. The undocumented stored procedure sp_MSForEachTable safely bypasses built-in limitations to accomplish this common task.
by Susan Sales Harkins
February 19, 2009
hether you develop custom database solutions or administer existing databases, you know that deleting records is a common task that's easy to automatemost of the time. However, deleting all the records in a SQL Server database can be a bit more challenging because a built-in safeguard prevents you from deleting related data. To work around this protection, you must know your data well and work through the tables manually in just the right order. Otherwise, you may violate constraints.
If you're automating the deletion process for the first time, you might consider Transact-SQL's DELETE or TRUNCATE commands, as both delete all the records from a table (with some limitations). If a constraint exists between the data in two or more tables, however, a DELETE or TRUNCATE will fail. In addition, both commands work with just one table at a time. If you want to delete all of the records from all of the tables in a SQL Server database while avoiding the constraint limitation, you have two options:
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!