SQLserver批量删除空表

今天需要清理一个很大的数据库,里面表有一堆,而且有很多是空表。想着把数据库弄小点,于是想到一次性删掉所有空表。

废话不多说,上代码。

首先,查处所有的空表。

select distinct a.name AS 表名 ,b.rows AS 表数据条数
from sys.objects  a,sysindexes b
where a.object_id=b.id and a.type='u' 
and b.rows = 0  --所有数据条数为0的表
View Code

然后把查询的表名拼成drop table的语句。

select 'drop table '+ a.name+';' from 
sys.objects a ,sysindexes b 
where type ='u' and a.object_id=b.id and b.rows = 0
View Code

这时候会发现查询结果都是drop语句。剩下的就把查询结果ctrl+A,然后ctrl+C,再ctrl+V,最后F5执行。。。。。。搞定,所有空表都删了。

原文地址:https://www.cnblogs.com/MirageFox/p/4953146.html