我有一堆数据库表,我想删除所有数据库。我的脚本如下......但是当我尝试运行时,我创建了一个无限循环。
我有什么想法可以做到这一点?
/* 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
答案 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
强>
工作原理:
请记住,如果您的表定义了外键,则丢弃的顺序很重要。
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