How to drop all tables from a database with one SQL query?
Use the INFORMATION_SCHEMA.TABLES view to get the list of tables. Generate Drop scripts in the select statement and drop it using Dynamic SQL:
DECLARE @sql NVARCHAR(max)=''
SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql @sql
Sys.Tables Version
DECLARE @sql NVARCHAR(max)=''
SELECT @sql += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM sys.tables t
JOIN sys.schemas s
ON t.[schema_id] = s.[schema_id]
WHERE t.type = 'U'
Exec sp_executesql @sql
Note: If you have any foreign Keys
defined between tables then first run the below query to disable all foreign keys
present in your database.
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
For more information, check here.
The simplest way is to drop the whole database and create it once again:
drop database db_name
create database db_name
That's all.
If you don't want to type, you can create the statements with this:
USE Databasename
SELECT 'DROP TABLE [' + name + '];'
FROM sys.tables
Then copy and paste into a new SSMS window to run it.
If you want to use only one SQL query to delete all tables you can use this:
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.
Note: You may need to execute the query a few times to delete all tables due to dependencies.
Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"