How to drop all tables from a database with one SQL query?

后端 未结 12 2073
盖世英雄少女心
盖世英雄少女心 2020-12-12 09:44

I don\'t want to type all tables\' name to drop all of them. Is it possible with one query?

相关标签:
12条回答
  • 2020-12-12 10:07

    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.

    0 讨论(0)
  • 2020-12-12 10:07

    For me I just do

    
    DECLARE @cnt INT = 0;
    
    WHILE @cnt < 10 --Change this if all tables are not dropped with one run
    BEGIN
    SET @cnt = @cnt + 1;
    EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
    END
    
    
    0 讨论(0)
  • 2020-12-12 10:08

    As a follow-up to Dave.Gugg's answer, this would be the code someone would need to get all the DROP TABLE lines in MySQL:

    SELECT CONCAT('DROP TABLE ', TABLE_NAME, ';')
    FROM INFORMATION_SCHEMA.tables
    WHERE TABLE_SCHEMA = 'your_database_name'
    
    0 讨论(0)
  • 2020-12-12 10:12

    Use the following script to drop all constraints:

    DECLARE @sql NVARCHAR(max)=''
    
    SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) +    ' NOCHECK CONSTRAINT all; '
    FROM   INFORMATION_SCHEMA.TABLES
    WHERE  TABLE_TYPE = 'BASE TABLE'
    
    Exec Sp_executesql @sql
    

    Then run the following to drop all tables:

    select @sql='';
    
    SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
    FROM   INFORMATION_SCHEMA.TABLES
    WHERE  TABLE_TYPE = 'BASE TABLE'
    
    Exec Sp_executesql @sql
    

    This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

    0 讨论(0)
  • 2020-12-12 10:16

    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.

    0 讨论(0)
  • 2020-12-12 10:20

    I'd just make a small change to @NoDisplayName's answer and use QUOTENAME() on the TABLE_NAME column and also include the TABLE_SCHEMA column encase the tables aren't in the dbo schema.

    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;
    

    Or using sys schema views (as per @swasheck's comment):

    DECLARE @sql nvarchar(max) = '';
    
    SELECT @sql += 'DROP TABLE ' + QUOTENAME([S].[name]) + '.' + QUOTENAME([T].[name]) + ';'
    FROM [sys].[tables] AS [T]
    INNER JOIN [sys].[schemas] AS [S] ON ([T].[schema_id] = [S].[schema_id])
    WHERE [T].[type] = 'U' AND [T].[is_ms_shipped] = 0;
    
    EXEC SP_EXECUTESQL @sql;
    
    0 讨论(0)
提交回复
热议问题