首页 > 解决方案 > 选择所有空数据库

问题描述

我正在清理一些数据库,并且正在寻找一个 t-sql 查询,它将向我显示所有没有任何表或视图的数据库。

从这个问题:https ://dba.stackexchange.com/questions/114958/list-all-tables-from-all-user-databases/230411#230411

我有一个查询将返回具有 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

标签: sqlsql-servertsql

解决方案


要获取数据库中表的计数,您可以发出以下命令:

declare @howmany int;

select @howmany=count(*) from sys.objects where type='U'
Select 'There are '+cast(@howmany as varchar(10)) +' tables in the database.';

推荐阅读