SQL Server 2005 檢視資料庫表的大小 按照表大小排列

衣舞晨風發表於2015-07-13
(1)Question:尼瑪一個資料庫,動輒幾十個G,傷不起啊,怎樣才能知道當前資料庫裡面各個表的大小呢?以便將部分較大的資料庫表中不容易被頻繁訪問的資料歸檔到歷史表中,例如每天將一個自然年以前的資料放入歷史表中。
(2)Key:網上搜了一圈,關鍵字sp_spaceused (參見:http://msdn.microsoft.com/zh-cn/library/ms188776.aspx)
(3)Sample:同時找到了一個示例(參見:http://www.linuxso.com/linuxxitongguanli/519.html 推薦: SQL Server 2005 檢視資料庫表的大小 按照表大小排列),下面就將這個示例的程式碼原樣抄寫下來,供大家分享啦!對了,我在2005上驗證過,程式碼沒有什麼大問題。
(4)Code:

(4.1)將表大小佔用情況存放到新建立的 tablespaceinfo表中

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tablespaceinfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
create table tablespaceinfo --建立結果儲存表
(nameinfo varchar(50) , 
rowsinfo int , reserved varchar(20) , 
datainfo varchar(20) , 
index_size varchar(20) , 
unused varchar(20) )

delete from tablespaceinfo --清空資料表

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
據說:

sp_spaceused的結果有時是不準確的, 要加updateusage選項才行,修改版:

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tablespaceinfo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
create table tablespaceinfo --建立結果儲存表
(nameinfo varchar(50) , 
rowsinfo int , reserved varchar(20) , 
datainfo varchar(20) , 
index_size varchar(20) , 
unused varchar(20) )

delete from tablespaceinfo --清空資料表

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,@updateusage=true',
N'@tbname varchar(255)',
@tbname = @tablename

FETCH NEXT FROM Info_cursor 
INTO @tablename 
END

CLOSE Info_cursor
DEALLOCATE Info_cursor
GO
(4.2)檢視當前資料庫大小情況

--itlearner注:顯示資料庫資訊
sp_spaceused @updateusage = 'TRUE' 
(4.3)檢視存放了當前資料庫各個表大小的tablespaceinfo表中記錄

--itlearner注:顯示錶資訊
select * 
from tablespaceinfo 
order by cast(left(ltrim(rtrim(reserved)) , len(ltrim(rtrim(reserved)))-2) as int) desc 

原文地址:http://bbs.csdn.net/topics/380068082



相關文章