获取SQL Server中每个数据库中的表数

时间:2015-05-14 09:47:59

标签: sql-server tsql sql-server-2005

RequiredFieldValidator

我有上面的T-SQL脚本,它列出了SQL Server实例上的所有数据库及其相应的大小(以MB为单位)。绿带。

我所挣扎的还包括每个数据库中表格数量的列。

是否有人也知道如何改进上述脚本以显示每个列出的数据库中的表总数。可选地,获得每个表中的行数也会很好,但这不是一个大问题。

我的目标是sql server 2005和obove。

2 个答案:

答案 0 :(得分:1)

不是单个脚本,您可以通过

获取请求的结果
CREATE TABLE AllTables ([DB Name] sysname, [Schema Name] sysname, [Table Name] sysname)


    DECLARE @SQL NVARCHAR(MAX)

    SELECT @SQL = COALESCE(@SQL,'') + '
    insert into AllTables
    select ' + QUOTENAME(name,'''') + ' as [DB Name], [Table_Schema] as 
    [Table Schema], [Table_Name] as [Table Name] from ' +
    QUOTENAME(Name) + '.INFORMATION_SCHEMA.Tables;' FROM sys.databases
    ORDER BY name 
    EXECUTE(@SQL)     
    SELECT * FROM AllTables ORDER BY [DB Name],[SCHEMA NAME], [Table Name]
    DROP TABLE AllTables

参考:List of All Tables in All Databases

答案 1 :(得分:1)

关于所有数据库的更广泛报告可能包括有关表格,视图,程序,触发器,便利设施(xml,空间索引)的统计信息,并且到目前为止。

if object_ID('TempDB..#AllTables','U') IS NOT NULL drop table #AllTables
CREATE TABLE #AllTables (
  [DB Name] sysname, 
  [Tables] int, 
  [Views] int, 
  [Procedures] int, 
  [Triggers] int, 
  [Full Text Catalogs] int, 
  [Xml Indexes] int, 
  [Spatial Indexes] int)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = COALESCE(@SQL,'') + 'USE ' + quotename(name) + '
insert into #AllTables 
select ' + QUOTENAME(name,'''') + ' as [DB Name], 
    (select count(*) from ' + QUOTENAME(Name) + '.sys.tables),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.views),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.procedures),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.triggers),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.fulltext_catalogs),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.xml_indexes),
    (select count(*) from ' + QUOTENAME(Name) + '.sys.spatial_indexes)
 '
FROM sys.databases
ORDER BY name
-- print @SQL -- debug 
EXECUTE(@SQL)
SELECT * FROM #AllTables

提供的解决方案远非最佳,易于掌握和扩展。

NOT OPTIMAL,仅适用于零星的报告

基于(和信用):http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-to-get-information-about-all-databas/