I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data.
What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.
Truncating all of the tables will only work if you don't have any foreign key relationships between your tables, as SQL Server will not allow you to truncate a table with a foreign key.
An alternative to this is to determine the tables with foreign keys and delete from these first, you can then truncate the tables without foreign keys afterwards.
See http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=65341 and http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72957 for further details.
The hardest part of truncating all tables is removing and re-ading the foreign key constraints.
The following query creates the drop & create statements for each constraint relating to each table name in @myTempTable. If you would like to generate these for all the tables, you may simple use information schema to gather these table names instead.
I then just copy out the statements to run - but with a bit of dev effort you could use a cursor to run them dynamically.
This is one way to do it... there are likely 10 others that are better/more efficient, but it sounds like this is done very infrequently, so here goes...
get a list of the
tables
fromsysobjects
, then loop over those with a cursor, callingsp_execsql('truncate table ' + @table_name)
for eachiteration
.Here's the king daddy of database wiping scripts. It will clear all tables and reseed them correctly:
Enjoy, but be careful!
For SQL 2005,
Couple more links for 2000 and 2005/2008..
It is much easier (and possibly even faster) to script out your database, then just drop and create it from the script.