Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop all tables from a database in sql server 2005 in a statement except one table

I am using sql-server 2005. Initially, for learning purpose I created many tables now I want to drop all those tables except one which is currently I am working on. Is there any code or query with which I can drop all tables from my that database except that one useful table. One way I think is to copy that table into new database using SELECT INTO... clause and drop that database but don't know is this a good way to solve this problem.

like image 872
Manish Avatar asked Oct 04 '11 11:10

Manish


1 Answers

If the tables aren't very big I'd probably just select them all in the "Object Explorer Details" window in SSMS then hit delete.

For a programmatic solution you could use

EXEC sys.sp_MSforeachtable 
       N'IF OBJECT_ID(''?'') <> OBJECT_ID(''dbo.YourTableToKeep'')
             DROP TABLE ?
       '

Both methods might need repeated runs in order to delete all tables involved in FK relationships (a table cannot be deleted if another table has an FK referencing it).

like image 195
Martin Smith Avatar answered Oct 05 '22 01:10

Martin Smith