关于sql server:如何使用一个SQL查询从数据库中删除所有表?

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

我不想键入所有表的名称来删除所有表。一个查询可以吗?


使用information_schema.tables视图获取表列表。在select语句中生成drop脚本,并使用动态SQL将其删除:

1
2
3
4
5
6
7
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

系统表版本

1
2
3
4
5
6
7
8
9
DECLARE @SQL NVARCHAR(MAX)=''

SELECT @SQL += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM   sys.tables t
       JOIN sys.schemas s
         ON t.[schema_id] = s.[schema_id]
WHERE  t.type = 'U'

EXEC sp_executesql @SQL

注意:如果在表之间定义了任何foreign Keys,那么首先运行下面的查询以禁用数据库中的所有foreign Keys

1
EXEC sp_msforeachtable"ALTER TABLE ? NOCHECK CONSTRAINT all"

有关详细信息,请查看此处。


如果只想使用一个SQL查询删除所有表,则可以使用它

1
EXEC sp_MSforeachtable @command1 ="DROP TABLE ?"

这是SQL Server中的一个隐藏存储过程,将为所连接的数据库中的每个表执行该过程。

注意:在运行上述查询之前,首先检查是否与任何表有外键关系。如果有,那么只需通过运行此查询禁用外键约束即可。

1
EXEC sp_msforeachtable"ALTER TABLE ? NOCHECK CONSTRAINT all"


如果不想键入,可以使用以下命令创建语句:

1
2
3
4
USE Databasename

SELECT  'DROP TABLE [' + name + '];'
FROM    sys.tables

然后复制并粘贴到一个新的SSMS窗口中以运行它。


您还可以使用以下脚本删除所有内容,包括:

  • 非系统存储过程
  • 意见
  • 功能
  • 外键约束
  • 主键约束
  • 桌子

https://michaelreichenbach.de/how-to-drop-everything-in-a-mssql-database/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

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

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [TYPE] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

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

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

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [TYPE] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

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

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [TYPE] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [TYPE] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @CONSTRAINT VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @CONSTRAINT = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @CONSTRAINT IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@CONSTRAINT) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @CONSTRAINT + ' on ' + @name
        SELECT @CONSTRAINT = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @CONSTRAINT AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @CONSTRAINT VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @CONSTRAINT = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @CONSTRAINT IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@CONSTRAINT)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @CONSTRAINT + ' on ' + @name
        SELECT @CONSTRAINT = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @CONSTRAINT AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* 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
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

我只需对@nodisplayname的答案做一个小改动,在TABLE_NAME列上使用QUOTENAME(),还包括TABLE_SCHEMA列,其中包含表不在dbo模式中。

1
2
3
4
5
6
7
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;

或者使用sys模式视图(根据@swasheck的注释):

1
2
3
4
5
6
7
8
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;


作为对dave.gugg答案的后续,这是一些人需要获取mysql中所有drop table行的代码:

1
2
3
SELECT CONCAT('DROP TABLE ', TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = 'your_database_name'


如果其他人对Best Answer的解决方案(包括禁用外键)有问题,我将提供另一个解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- CLEAN DB
USE [DB_NAME]
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
DECLARE @SQL NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT SQL = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @SQL
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC SP_EXECUTESQL @SQL
FETCH NEXT FROM @Cursor INTO @SQL
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'

dropall constraints使用以下脚本:

1
2
3
4
5
6
7
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

然后运行以下命令删除所有表:

1
2
3
4
5
6
7
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

这在我的Azure SQL数据库中很有用,因为'sp_msforeachtable'不可用!


不完全是一个问题,仍然很简短和甜蜜:

1
2
3
4
5
6
7
8
9
10
11
12
13
-- Disable all referential integrity constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
DECLARE @SQL nvarchar(MAX)
SELECT @SQL = STUFF((SELECT '; ' + 'ALTER TABLE ' + TABLE_NAME  +'  drop constraint ' + Constraint_Name  FROM Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@SQL)
GO

-- Drop all tables
EXEC sp_msforeachtable 'DROP TABLE ?'
GO

最简单的方法是删除整个数据库,然后再次创建它:

1
2
DROP DATABASE db_name
CREATE DATABASE db_name

这就是全部。


我知道这个问题很古老,但每次我需要这个代码时……顺便说一下,如果您有表、视图、函数和过程,您可以通过这个脚本将它们全部删除。所以我为什么要发布这个脚本??因为如果删除所有表,您将需要删除所有视图,如果您有函数和过程,您也需要删除它。我希望它能帮助别人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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


 DECLARE @SQL VARCHAR(MAX) = ''
    , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

 SELECT @SQL = @SQL + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
 QUOTENAME(v.name) +';' + @crlf
 FROM   sys.views v

 PRINT @SQL;
 EXEC(@SQL);

 DECLARE @procName VARCHAR(500)
 DECLARE cur cursor

 FOR SELECT [name] FROM sys.objects WHERE TYPE = 'p'
 OPEN cur
 fetch NEXT FROM cur INTO @procName
 while @@fetch_status = 0
 BEGIN
  EXEC('drop procedure [' + @procName + ']')
fetch NEXT FROM cur INTO @procName
 END
  close cur
  deallocate cur

  DECLARE @SQL NVARCHAR(MAX) = N'';

    SELECT @SQL = @SQL + N' DROP FUNCTION '
               + QUOTENAME(SCHEMA_NAME(schema_id))
               + N'.' + QUOTENAME(name)
    FROM sys.objects
  WHERE type_desc LIKE '%FUNCTION%';

   EXEC sp_executesql @SQL
  GO