sql server查询数据库的大小和各数据表的大小

时间:2023-03-09 09:21:18
sql server查询数据库的大小和各数据表的大小

查询出来的结果中各字段的详细说明参考MSDN资料:https://msdn.microsoft.com/zh-cn/library/ms188776.aspx

如果只是查询数据库的大小的话,直接使用以下语句即可:

EXEC sp_spaceused

为了保证查询结果的实时性,推荐使用 @updateusage 参数来确保统计数据是最新的:

EXEC sp_spaceused @updateusage = N'TRUE';

执行完毕后结果是两个表,第一个表中包含了基本的统计信息,第二个表示更加详细的数据占用情况。

sql server查询数据库的大小和各数据表的大小

如果想具体查询某个表的大小,加上表名即可:

sql server查询数据库的大小和各数据表的大小

如果想要一次性的把数据库中所有的表的大小全部查询出来的话,参考下面的方法:

-- =============================================
-- Description: 更新查询数据库中各表的大小,结果存储到数据表中
-- =============================================
create procedure [dbo].[sp_UpdateTableSpaceInfo] AS
begin
--查询是否存在结果存储表
if not exists (select * from sysobjects where id = object_id(N'temp_tableSpaceInfo') AND objectproperty(id, N'IsUserTable') = 1)
begin
--不存在则创建
create table temp_tableSpaceInfo
(name nvarchar(128),
rows char(11),
reserved varchar(18),
data varchar(18),
index_size varchar(18),
unused varchar(18))
end
--清空数据表
delete from temp_tableSpaceInfo --定义临时变量在遍历时存储表名称
declare @tablename varchar(255) --使用游标读取数据库内所有表表名
declare table_list_cursor cursor for --申明游标
select name from sysobjects
where objectproperty(id, N'IsTable') = 1 and name not like N'#%%' order by name --打开游标
open table_list_cursor
--将提取结果代入游标
fetch next from table_list_cursor into @tablename --遍历查询到的表名
while @@fetch_status = 0 --最近一条FETCH语句的标志
begin
--检查当前表是否为用户表
if exists (select * from sysobjects where id = object_id(@tablename) AND objectproperty(id, N'IsUserTable') = 1)
begin
--当前表则读取其信息插入到表格中
execute sp_executesql N'insert into temp_tableSpaceInfo exec sp_spaceused @tbname', N'@tbname varchar(255)', @tbname = @tablename
end
--读取下一条数据
fetch next from table_list_cursor into @tablename
end --释放游标
close table_list_cursor --解除游标
deallocate table_list_cursor --将游标内容代入最后结果
end GO

用的时候呢,执行一下:

EXEC sp_UpdateTableSpaceInfo
SELECT * FROM temp_tableSpaceInfo

OK,搞定!