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

后端 未结 12 2100
盖世英雄少女心
盖世英雄少女心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    

提交回复
热议问题