我试图删除除2个表之外的所有非系统表。但它总是删除 所有的表格。
这段代码我做错了什么?
/* 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
AND name NOT IN ('JobSource', 'City')
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
答案 0 :(得分:1)
当您在结尾处更新@name变量时,您忘记将名称条件添加到内循环的WHERE
子句中。
像这样改变你的循环(注意最后的SELECT
语句):
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 not in ('JobSource', 'City') ORDER BY [name])
END
另外,你可能不需要该子句中的AND [name] > @name
所以我把它拿出来了。