我在工作中碰到了一些問題,需要查看數(shù)據(jù)庫表的大小,查詢SQL Server聯(lián)機(jī)從書得到如下語句:
顯示行數(shù)、保留的磁盤空間以及當(dāng)前數(shù)據(jù)庫中的表所使用的磁盤空間,或顯示由整個數(shù)據(jù)庫保留和使用的磁盤空間。
sp_spaceused [[@objname =] 'objname']
[,[@updateusage =] 'updateusage']
[@objname =] 'objname'
是為其請求空間使用信息(保留和已分配的空間)的表名。objname 的數(shù)據(jù)類型是 nvarchar(776),默認(rèn)設(shè)置為 NULL。
[@updateusage =] 'updateusage'
表示應(yīng)在數(shù)據(jù)庫內(nèi)(未指定 objname 時)還是在特定的對象上(指定 objname 時)運(yùn)行 DBCC UPDATEUSAGE。值可以是 true 或 false。updateusage 的數(shù)據(jù)類型是 varchar(5),默認(rèn)設(shè)置為 FALSE。
0(成功)或 1(失敗)
下例報告為 titles 表分配(保留)的空間量、數(shù)據(jù)使用的空間量、索引使用的空間量以及由數(shù)據(jù)庫對象保留的未用空間量。
USE pubsEXEC sp_spaceused 'titles'下例概括當(dāng)前數(shù)據(jù)庫使用的空間并使用可選參數(shù) @updateusage。
USE pubssp_spaceused @updateusage = 'TRUE'不過此方法,只能查看一個表的大小,一個數(shù)據(jù)庫中一般會有多個表,如何一次性查看某數(shù)據(jù)庫的所有表大小呢?
第一種方法(較簡單,看的有些吃力):
exec sp_MSforeachtable "exec sp_spaceused '?'"
第二種方法(較復(fù)雜,但看的比較清楚,原作者不詳):
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tablespaceinfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
create table tablespaceinfo --創(chuàng)建結(jié)果存儲表
(nameinfo varchar(50) ,
rowsinfo int , reserved varchar(20) ,
datainfo varchar(20) ,
index_size varchar(20) ,
unused varchar(20) )
delete from tablespaceinfo --清空數(shù)據(jù)表
declare @tablename varchar(255) --表名稱
declare @cmdsql varchar(500)
DECLARE Info_cursor CURSOR FOR
select o.name
from dbo.sysobjects o where OBJECTPROPERTY(o.id, N'IsTable') = 1
and o.name not like N'#%%' order by o.name
OPEN Info_cursor
FETCH NEXT FROM Info_cursor
INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
if exists (select * from dbo.sysobjects where id = object_id(@tablename) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
execute sp_executesql
N'insert into tablespaceinfo exec sp_spaceused @tbname',
N'@tbname varchar(255)',
@tbname = @tablename
FETCH NEXT FROM Info_cursor
INTO @tablename
END
CLOSE Info_cursor
DEALLOCATE Info_cursor
GO
--VeVb注:顯示數(shù)據(jù)庫信息
sp_spaceused @updateusage = 'TRUE'
--VeVb注:顯示表信息
select *
from tablespaceinfo
order by cast(left(ltrim(rtrim(reserved)) , len(ltrim(rtrim(reserved)))-2) as int) desc
第三種方法:
select object_name(id) tablename,8*reserved/1024 reserved,rtrim(8*dpages/1024)+'Mb' used,8*(reserved-dpages)/1024 unused,8*dpages/1024-rows/1024*minlen/1024 free,
rows,* from sysindexes
where indid=1
order by reserved desc
新聞熱點(diǎn)
疑難解答
圖片精選