如何删除除1之外的所有表

时间:2016-05-25 19:00:33

标签: sql sql-server sql-server-2008 tsql

我有一堆数据库表,我想删除所有数据库。我的脚本如下......但是当我尝试运行时,我创建了一个无限循环。

我有什么想法可以做到这一点?

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects 
                WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL 
IF @name !=  'tableNotToBeDropped'
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects  
                    WHERE [type] = 'U' AND category = 0 AND [name] > @name 
                    ORDER BY [name])
END
GO

3 个答案:

答案 0 :(得分:7)

根本不需要循环。 DROP TABLE可以使用一个语句删除多个表:

DECLARE @tables NVARCHAR(MAX) = 
         STUFF((SELECT ',' + QUOTENAME([table_name]) AS [text()]  
               FROM INFORMATION_SCHEMA.TABLES
               WHERE table_schema = 'dbo' 
               AND TABLE_NAME <> 'tableNotToBeDropped'
               FOR XML PATH('')),1,1,'');

DECLARE @sql NVARCHAR(MAX) = 'DROP TABLE ' + @tables;

-- debug
SELECT @sql;

EXEC sp_executesql @sql;

LiveDemo

工作原理:

  1. 获取除一个
  2. 之外的特定架构的所有表名
  3. 创建逗号分隔列表
  4. 删除表
  5. 请记住,如果您的表定义了外键,则丢弃的顺序很重要。

    编辑:

    SQL Server 2017版:

    DECLARE @sql NVARCHAR(MAX) = 'DROP TABLE IF EXISTS ' 
                + (SELECT string_agg(QUOTENAME(table_name), ',')
                   FROM INFORMATION_SCHEMA.TABLES
                   WHERE table_schema = 'dbo' 
                   AND TABLE_NAME <> 'tableNotToBeDropped'
                   AND TABLE_NAME LIKE 't%');
    
    SELECT @sql;
    EXEC sp_executesql @sql;
    

    <强> DBFiddle Demo

答案 1 :(得分:1)

这一个班轮也有效:

sp_MSforeachtable @command1='IF OBJECT_ID(''?'') NOT IN (OBJECT_ID(''TableToNotDelete'')) DROP TABLE ?'

答案 2 :(得分:-1)

我建议您使用游标,并将名称不等于游标查询的where子句。

http://www.kodyaz.com/articles/sql-cursor-example-tables-rows-count-using-sql-server-cursor.aspx