代码改变世界

sqlserver列出数据库中的表和表中的行数

2022-04-19 11:01  abce  阅读(104)  评论(0编辑  收藏  举报
select schema_name(tab.schema_id) + '.' + tab.name as [ table ],
       sum(part.rows) as [ rows ]
  from sys.tables tab
 inner join sys.partitions part
    on tab.object_id = part.object_id
 where part.index_id IN (1, 0) -- 0 - table without PK, 1 table with PK
 group by schema_name(tab.schema_id) + '.' + tab.name
 order by sum(part.rows) desc

  

select 
     sch.name as SchemaName,
     tab.name as TableName,
     par.rows as RowCounts, 
     sum(alc.total_pages) * 8 as TotalSpace,
     sum(alc.used_pages) * 8 as UsedSpace,
     (sum(alc.total_pages) - sum(alc.used_pages)) * 8 as UnusedSpace
FROM sys.tables tab 
INNER JOIN sys.indexes ind 
     ON tab.object_id = ind.object_id 
INNER JOIN sys.partitions par 
     ON ind.object_id = par.object_id 
     and ind.index_id = par.index_id 
INNER JOIN sys.allocation_units alc 
     ON par.partition_id = alc.container_id 
LEFT OUTER JOIN sys.schemas sch 
     ON tab.schema_id = sch.schema_id 
GROUP BY 
     tab.name, 
     sch.name, 
     par.rows 
ORDER BY 3 desc;