查詢資料庫中所有表的資料數量的方法

2021-07-10 09:16:38 字數 2278 閱讀 1996

要查詢乙個表的資料數量,相信大家很快就想到了select count(1) from table1,但如果我們要查詢資料庫中所有表的的資料數量要怎麼查呢?方法比較多,下面介紹兩種本人常用的方法:

一,利用sp_spaceused儲存過程,sp_spaceused一次只能查詢乙個表的資料情況,所以使用sp_spaceused還得結合游標,不是很好的解決方法,大家可以參考第二種方法:

利用sp_spaceused的方法如下:

set nocount on

create table #t1 (

name varchar(200),

rows int,

reserved varchar(50),

data varchar(50),

index_size varchar(50),

unused varchar(50) )

declare @tablename varchar(200)

declare @sql varchar(2000)

declare m_cursor cursor local for select object_name(object_id) from sys.objects where type='u'

open m_cursor

fetch next from m_cursor into @tablename

while @@fetch_status=0

begin

set @sql='insert into #t1 exec sp_spaceused '+@tablename

exec(@sql)

fetch next from m_cursor into @tablename

endclose m_cursor

deallocate m_cursor

select name,rows from #t1

drop table #t1

簡單介紹一下儲存過程sp_spaceused作用:顯示行數、保留的磁碟空間以及當前資料庫中的表、索引檢視或 sql server 2005 service broker 佇列所使用的磁碟空間,或顯示由整個資料庫保留和使用的磁碟空間。

如果我們這樣執行:sp_spaceused 表名

它會返回六列結果,截圖如下:

name:表名

rows:該錶的資料行數

reserved:由資料庫中物件分配的空間總量

data:資料使用的空間總量

index_size:索引使用的空間總量

unused:保留但尚未使用的空間總量

其中rows就是我們要的結果列。

二,利用sys.dm_db_partition_stats,sql命令如下:

select b.name,a.row_count from sys.dm_db_partition_stats a,

sys.objects b

where a.object_id=b.object_id 

and a.index_id<=1

and b.type='u'

sys.dm_db_partition_stats它返回當前資料庫中每個分割槽的頁和行計數資訊,在上面的sql中,三個關鍵列的意思如下:

object_id:表或者索引檢視的id,所以可以用它與sys.objects表的object_id相匹配。

row_count:該錶或索引檢視中資料的數量,就是我們要查詢的結果。

index_id:該錶或索引檢視的索引id。 如果該錶沒有索引,那麼會在sys.dm_db_partition_stats中存在一行index_id=0的記錄,如果有乙個聚集索引(而且乙個表中也只能有乙個聚集索引),那麼在sys.dm_db_partition_stats中存在一行index_id=1的記錄,而對應的index_id=0的記錄沒有了。如果這個表在sys.dm_db_partition_stats中存在多行index_id >1的記錄,則說明這個表存在多個非聚集索引,我們這裡判斷index_id<=1,是假定每個表都有主鍵,且主鍵為聚集索引。配合sys.objects表的type='u',就可以查出每個使用者表的資料數量了。

sys.dm_db_partition_stats其它行的資訊,大家可以查詢msdn幫助文件。

查詢資料庫中所有的表

select from sysobjects where xtype u 查詢當前資料庫下所有使用者建立的表 xtype char 2 物件型別。可以是下列物件型別中的一種 c check 約束 d 預設值或 default 約束 f foreign key 約束 l 日誌 fn 標量函式 if 內...

查詢資料庫中所有表名,查詢表中所有欄位名

mysql 1.查詢資料庫中所有表名稱 select table name from information schema.tables where table schema 資料庫名稱 包含檢視 select table name from information schema.tables wh...

查詢資料庫中所有列名

如何從整個資料庫所有表中查詢出乙個列名?比如想要查詢乙個名為 name 的列名,但是忘記了這一列是在那乙個表中,需要從整個資料庫的所有表中進行查詢。oracle 資料庫 select from user col comments s where s.column name like name mys...