How to drop all tables in a SQL Server database? How to drop all tables in a SQL Server database? sql-server sql-server

How to drop all tables in a SQL Server database?


You can also delete all tables from database using only MSSMS UI tools (without using SQL script). Sometimes this way can be more comfortable (especially if it is performed occasionally)

I do this step by step as follows:

  1. Select 'Tables' on the database tree (Object Explorer)
  2. Press F7 to open Object Explorer Details view
  3. In this view select tables which have to be deleted (in this case all of them)
  4. Keep pressing Delete until all tables have been deleted (you repeat it as many times as amount of errors due to key constraints/dependencies)


It doesn't work for me either when there are multiple foreign key tables.
I found that code that works and does everything you try (delete all tables from your database):

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSORSET @Cursor = CURSOR FAST_FORWARD FORSELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' +  tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAMEOPEN @Cursor FETCH NEXT FROM @Cursor INTO @SqlWHILE (@@FETCH_STATUS = 0)BEGINExec sp_executesql @SqlFETCH NEXT FROM @Cursor INTO @SqlENDCLOSE @Cursor DEALLOCATE @CursorGOEXEC sp_MSforeachtable 'DROP TABLE ?'GO

You can find the post here. It is the post by Groker.


In SSMS:

  • Right click the database
  • Go to "Tasks"
  • Click "Generate Scripts"
  • In the "Choose Objects" section, select "Script entire database and all database objects"
  • In the "Set Scripting Options" section, click the "Advanced" button
  • On "Script DROP and CREATE" switch "Script CREATE" to "Script DROP" and press OK
  • Then, either save to file, clipboard, or new query window.
  • Run script.

Now, this will drop everything, including the database. Make sure to remove the code for the items you don't want dropped. Alternatively, in the "Choose Objects" section, instead of selecting to script entire database just select the items you want to remove.