sql - 选择所有空数据库
问题描述
我正在清理一些数据库,并且正在寻找一个 t-sql 查询,它将向我显示所有没有任何表或视图的数据库。
我有一个查询将返回具有 0 条记录的表,但它错过了那些没有任何表的数据库。
If Exists (Select * From tempdb.dbo.sysobjects o Where o.xtype in ('U') And o.id = object_id (N'tempdb..#temptable')) Begin Drop Table #temptable End
DECLARE @src NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @sql = N'', @src = N' UNION ALL
SELECT ''$d'' as ''database'',
s.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''schema'',
t.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''table'' ,
ind.rows as record_count
FROM [$d].sys.schemas AS s
INNER JOIN [$d].sys.tables AS t ON s.[schema_id] = t.[schema_id]
INNER JOIN [$d].sys.sysindexes AS ind ON t.[object_id] = ind.[id]
--where ind.indid < 2';
SELECT @sql = @sql + REPLACE(@src, '$d', name)
FROM sys.databases
WHERE database_id > 4
AND [state] = 0
AND HAS_DBACCESS(name) = 1;
SET @sql = STUFF(@sql, 1, 10, CHAR(13) + CHAR(10));
create table #temptable (
database_name varchar(max) null,
schema_name varchar(max) null,
table_name varchar(max) null,
record_count int null
)
insert into #temptable
EXEC sys.sp_executesql @sql;
select * from #temptable where record_count = 0 order by 1,2,3,4
解决方案
要获取数据库中表的计数,您可以发出以下命令:
declare @howmany int;
select @howmany=count(*) from sys.objects where type='U'
Select 'There are '+cast(@howmany as varchar(10)) +' tables in the database.';
推荐阅读
- swift - iOS - 如何在我的相机会话中处理音频记录?
- spring-boot - spring boot - 在调用方法运行之前加载应用程序配置
- python - 如何检测是否在 ModelForm.clean 中添加或编辑了 obj?
- ros - 如何在 PointCloud 的 sensor_msgs/Image 中保存强度值?
- python-3.x - 带有滚动条的 Tkinter Python 框架
- drupal - 我在 Twig 中有这个,变量吐出所有调试代码,而只是一个链接,我该怎么办?
- asp.net - C# 控制台不打印异常消息
- c++ - c++模板参数自动模板推导失败
- android - 使用android导航组件获取Backstack状态
- php - 使用 Symfony 3.4 图像的 URL