Created
July 6, 2011 06:58
-
-
Save aturgarg/1066701 to your computer and use it in GitHub Desktop.
truncating all tables in DB with foriegn key constraints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --http://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql | |
| --When dealing with deleting data from tables which have foreign key relationships - which is basically the -----case with any properly designed database - we can disable all the constraints, delete all the data and then ---re-enable constraints | |
| -- disable all constraints | |
| EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" | |
| -- delete data in all tables | |
| EXEC sp_MSForEachTable "DELETE FROM ?" | |
| -- enable all constraints | |
| exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" | |
| --if some of the tables have identity columns we may want to reseed(start identity element from 1) them | |
| EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment