查詢出來的結果中各字段的詳細說明參考MSDN資料:https://msdn.microsoft.com/zh-cn/library/ms188776.aspx
如果只是查詢數據庫的大小的話,直接使用以下語句即可:
EXEC sp_spaceused
為了保證查詢結果的實時性,推薦使用 @updateusage 參數來確保統計數據是最新的:
EXEC sp_spaceused @updateusage = N'TRUE';
執行完畢后結果是兩個表,第一個表中包含了基本的統計信息,第二個表示更加詳細的數據占用情況。
如果想具體查詢某個表的大小,加上表名即可:
如果想要一次性的把數據庫中所有的表的大小全部查詢出來的話,參考下面的方法:
-- ============================================= -- 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,搞定!