區分SQL資料庫資料表大小

2021-09-30 09:03:07 字數 2475 閱讀 6741

在工作中,你可能也曾被同樣的問題所困擾,即如何確定乙個資料庫所有資料表的大小。很遺憾的是,在sql中,並沒有乙個簡單而直觀的方法來檢視資料庫中所有表的大小,但是系統提供了乙個有用的儲存過程sp_spaceused ,只要我們充分利用、稍加變通,即可得到我們所需要的資訊。

sp_spaceused可用來查詢行數、保留的磁碟空間以及當前資料庫中的表所使用的磁碟空間,或顯示由整個資料庫保留和使用的磁碟空間。

執行儲存過程(exec sp_spaceused 資料表名),即可得到這個表的行數,占用空間大小等資訊,但是執行這個過程一次只能查詢乙個表的資訊,如何能一次查詢資料庫中所有表的資訊,這就需要我們另闢蹊徑。

在sql資料庫中,有乙個儲存所有資料表名的系統表sysobjects,根據這個表取出的資料表名,我們就可以利用sp_spaceused通過編寫查詢語句而一次性得到所有資料表的資訊。

一、首先建立乙個表用來儲存查詢資料表的結果:(//後內容為注釋)

create table tablespaceinfo(  //表名

nameinfo varchar(50),    //資料表名

rowsinfo int,            //表中現有的行數

reserved varchar(20),   //表保留的空間總量

datainfo varchar(20),   //表中的資料所使用的空間量

index_size varchar(20), //表中的索引所使用的空間量

unused varchar(20)    //表中未用的空間量 )

二、利用游標從系統表中逐個取出表名

declare @tablename varchar(255);  //存放資料表名的變數

declare info_cursor cursor for  //定義游標

select [name] from sysobjects where type='u';  

//從系統表中取出表型別為使用者的表名

open info_cursor  //開啟游標

fetch next from info_cursor into @tablename  //取資料表名到@tablename

三、根據取出的表名執行儲存過程,將查詢結果插入到我們在步驟一中所建立的表tablespaceinfo中。

while @@fetch_status = 0  

begin 

insert into @tablespaceinfo exec sp_spaceused @tablename 

// 將查詢結果插入表tablespaceinfo

fetch next from info_cursor  

into @tablename  

end 

四、關閉游標,從表tablespaceinfo查詢所有資料表的大小資訊

close info_cursor  

deallocate info_cursor  

//關閉游標

select * from tablespaceinfo  order by rowsinfo desc

//按行數從大到小排列資料表的大小資訊

總結:至此,我們已給出如何利用sp_spaceused獲取所有資料表大小資訊的完整步驟,在實際操作中,選中所需要查詢的資料庫,開啟查詢分析器,將下面的相應的**拷貝到查詢分析器中,執行該**即可得到資料表大小的資訊。現將完整查詢語句羅列如下:

create table tablespaceinfo(  

nameinfo varchar(50),  

rowsinfo int,  

reserved varchar(20),  

datainfo varchar(20),  

index_size varchar(20),  

unused varchar(20)  

)  

declare @tablename varchar(255);  

declare info_cursor cursor for 

select [name] from sysobjects where type='u';  

open info_cursor  

fetch next from info_cursor into @tablename  

while @@fetch_status = 0  

begin 

insert into tablespaceinfo exec sp_spaceused @tablename  

fetch next from info_cursor  

into @tablename  

end 

close info_cursor  

deallocate info_cursor  

select * from tablespaceinfo  

order by rowsinfo desc 

通過SQL建立資料庫 資料表

insert into class cname,cdescription values t001 這是乙個高階班,人數50 insert into class cname,cdescription values t002 這是乙個高階班,人數60 drop database myschool cre...

MySQL 資料庫 資料表

1 檢視原始資料庫information schema中的表,並顯示出views表的字段結構屬性資訊 第一步 檢視所有的資料庫 show databases 如圖一 第二步 檢視information schema 內容 如圖二 第三步 檢視views 結構 如圖三 2 建立乙個offcn資料庫,並...

mysql 3資料庫 資料表 sql檔案

資料庫 資料表 刪除表字段 alter table 表名 drop 表頭 注 如果資料表中只剩餘乙個欄位則無法使用drop來刪除字段。刪除列 alter table 表名 drop column 表頭 刪除改表頭對應的列 查詢資料 select 表頭 from 資料表 重新命名資料表renameta...