sql

Remove all tables from database using MSSQL query

MSSQL contains a store procedure - sp_MSforeachtable that can be used to remove or drop all tables from the database.

-- First remove all foreign key constraints between tables
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

-- Execute below query to drop tables from database
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

In the code snippet, we first remove all the foreign key constraints binding from the tables and then remove all tables by executing the sp_MSforeachtable store procedure.

Was this helpful?