1

How do I drop all the tables in a DB from Microsoft SQL Server Management Studio? Is it possible with one query?

I don't want to click on individual tables or type the name of individual tables in the query to drop them.

1 Answer 1

1

Here's what I sometimes use:

DECLARE @T NVARCHAR(255)
,       @S NVARCHAR(255)
,       @Type VARCHAR(255)
,       @SQL NVARCHAR(MAX)

EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

DECLARE crs CURSOR FAST_FORWARD
FOR
SELECT      QUOTENAME(T.TABLE_SCHEMA)
,           QUOTENAME(T.TABLE_NAME)
,           T.TABLE_TYPE
FROM        INFORMATION_SCHEMA.TABLES T
-- Add where clause if you don't want to clear all schema's, or want to keep some tables.

OPEN crs
FETCH NEXT FROM crs INTO @S, @T, @Type
WHILE @@FETCH_STATUS = 0

BEGIN
    IF @Type = 'BASE TABLE'
        SET @SQL = CONCAT(N'DROP TABLE ', @S, '.',  @T)
    IF @Type = 'VIEW'
        SET @SQL = CONCAT(N'DROP VIEW ', @S, '.',  @T)

    EXEC sys.sp_executesql @SQL

    FETCH NEXT FROM crs INTO @S, @T, @Type
END

CLOSE crs
DEALLOCATE crs
Sign up to request clarification or add additional context in comments.

4 Comments

It doesn't take care of resolving tables with foreign keys? Could not drop object 'sometable' because it is referenced by a FOREIGN KEY constraint.
@LokeshAgrawal, just added a note concerning FK's
@LokeshAgrawal You can add EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" as a small hack at the top of the script to not check for constraints.
@Justin Thanks, I've added it to the anwer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.