删除查询中出现的所有SQL表

时间:2018-07-02 20:10:17

标签: sql sql-server ssms sql-server-2016

我正在尝试开发一个脚本来比较两个数据库,以确定其中一个额外的表,然后删除这些表。这是我当前用于查找无关表的脚本:

-- Any location where TARGET appears, replace TARGET with the database to be 
-- modified
-- Any location where MODEL appears, replace MODEL with the database being 
-- used as a model for comparison

select 'TARGET' as dbname, t1.table_name
from TARGET.[INFORMATION_SCHEMA].[tables] as t1
where table_name not in (select t2.table_name
from 
MODEL.[INFORMATION_SCHEMA].[tables] as t2  
)

这给了我所需的结果,但是现在我需要解决如何删除表。恐怕我现在完全迷失了。也不介意声明变量而不是重复输入DBname的方法,但不确定在这种情况下我可以这样做。

2 个答案:

答案 0 :(得分:2)

您可以使用动态SQL:

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

select @sql += CONCAT('DROP TABLE ',QUOTENAME(t1.table_name,''''),';',CHAR(13))
from TARGET.[INFORMATION_SCHEMA].[tables] as t1
where table_name not in (select t2.table_name
                        from MODEL.[INFORMATION_SCHEMA].[tables] as t2);

SELECT @sql; -- debug
--EXEC(@sql);

编辑:

MySQL(可能需要挑剔):

SET @s = (select GROUP_CONCAT('DROP TABLE ''' + t1.table_name + ''';' SEPARATOR CHAR(13))
         from TARGET.INFORMATION_SCHEMA.tables as t1
         where table_name not in (select t2.table_name
                                  from MODEL.INFORMATION_SCHEMA.tables as t2));
SELECT @s; -- debug
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

我的直接想法是为查询中的每个结果分配一个行号,并将结果放入临时表中。使用从1开始的while循环,循环遍历该临时表中的最大数目,以获取将行号分配给每个循环的表的名称。使用该名称从数据库中删除。

select 'TARGET' as dbname, t1.table_name
     , ROW_NUMBER() OVER (Partition By t1.table_name) AS RowNumber
INTO #temp
from TARGET.[INFORMATION_SCHEMA].[tables] as t1
where table_name not in (select t2.table_name
                         from MODEL.[INFORMATION_SCHEMA].[tables] as t2)

DECLARE @counter INT = 1
DECLARE @maxNum INT
SELECT @maxNum = MAX(RowNumber) FROM #temp

While @counter <= @maxNum
   BEGIN
       DECLARE @tableName AS VARCHAR(MAX)
       SELECT @tableName = table_name FROM #temp WHERE RowNumber = @counter

       DELETE TABLE @tableName ' This may not be possible, but follow my lead

       @counter += 1
   END

DROP TABLE #temp

我不确定“ DELETE TABLE @tableName”是否正确,但是使用我给您的内容可能有非常相似的解决方案。我认为这是T-SQL。