How do I delete all tables from a database using a single SQL query?

Forums SQLHow do I delete all tables from a database using a single SQL query?
Staff asked 2 years ago

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

To delete all tables from a database using a single SQL query, you can use dynamic SQL to generate a list of all tables in the database and then execute a series of DROP TABLE statements based on that list. Here is an example SQL query that demonstrates how to do this:

 

DECLARE @table_names TABLE (table_name varchar(255))

INSERT INTO @table_names
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'base table' AND table_catalog = 'your_database_name'

DECLARE @table_name varchar(255)

WHILE EXISTS(SELECT TOP 1 1 FROM @table_names)
BEGIN
    SELECT TOP 1 @table_name = table_name FROM @table_names

    EXEC ('DROP TABLE ' + @table_name)

    DELETE FROM @table_names WHERE table_name = @table_name
END

In this query, the information_schema.tables system table is used to retrieve a list of all tables in the database. The list is stored in a temporary table variable called @table_names.

Next, a WHILE loop is used to iterate through the list of table names in @table_names. For each table name, a dynamic SQL statement is constructed that contains a DROP TABLE statement for that table.

The dynamic SQL statement is executed using the EXEC command. After the table has been dropped, the table name is removed from the @table_names variable so that the loop can move on to the next table.

By using this SQL query, you can delete all tables from a database using a single query. Note that this query should be used with caution, as it will permanently delete all tables and their data from the database. It is recommended that you take a backup of your database before running this query.

Subscribe

Select Categories