Thursday, October 06, 2011

How to truncate all tables in a SQL Server database?

1. For those who are adamant to do it via scripts: :)

Few years back I have written a t-sql script to do this. I have disabled the constraints before truncating the data and once it is done have enabled it back. But I guess in the latest versions of SQL Server we might need to drop & recreate the constraints (haven't tried it yet).

2. Generate Scripts:

If we need to return back to complete empty database with just table schema and other SQL Objects like Stored procedure, trigger, constraints etc., then it would be simple to script out the whole database. That way we can just drop and recreate the database anytime using those scripts.

3. Backup/Restore:

If we need to achieve what's mentioned in point 2 and along with that if we need few tables to have the master entries preserved so that our application can work properly! then why not take a Full backup of the database once everything is set in it. So that when ever we want to revert back to that state we can restore it back from that backup.

No comments: