erdeni 学无止境

MSSQL数据库统计所有表的记录数

今天需要筛选出来库中行数不为零的表,于是动手写下了如下存储过程。

CREATE PROCEDURE TableCount AS 
BEGIN
SET NOCOUNT ON
DECLARE @t1 AS TABLE(id INT IDENTITY,NAME NVARCHAR(50),RowsCount INT)
DECLARE @indexid AS INT
DECLARE @maxid AS INT
DECLARE @count AS INT
DECLARE @name AS VARCHAR(50)
DECLARE @sqlstr AS NVARCHAR(500)
INSERT INTO @t1 SELECT NAME,0 FROM dbo.sysobjects WHERE type='U'
SELECT @maxid=MAX(id),@indexid=1 FROM @t1
WHILE(@maxid>=@indexid)
BEGIN
SELECT @name = name FROM @t1 WHERE id=@indexid
SET @sqlstr = 'SELECT @Count1=COUNT(0) FROM '+@name
exec sp_executesql @sqlstr,N'@Count1 int output',@count output
UPDATE @t1 SET RowsCount=@count WHERE  id=@indexid
SET @indexid=@indexid+1
END
SET NOCOUNT OFF
SELECT * FROM @t1 WHERE RowsCount>0
END
GO
EXEC TableCount
GO

这样大功告成!

 

事后上网查阅相关资料发现有更简便的方法,贴在这里供大家参考吧。

CREATE TABLE #temp (Name VARCHAR (255), RowsCount INT)
EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(0) FROM ?'
SELECT Name, RowsCount FROM #temp WHERE RowsCount>0 ORDER BY Name
DROP TABLE #temp

注: 系统存储过程sp_MSforeachtable和sp_MSforeachdb,用于遍历每个表和遍历每个数据库。


总结,遇到问题还是先查一下有没有现成的方法能省不少的时间的,而且还可以学习到新的知识。

 

@空紫竹 提供的更快捷的方法: (2015-03-27编辑)

select rows,OBJECT_NAME(id) as TABLENAME 
from sysindexes 
where indid=0

 

posted on 2015-03-19 16:23  erdeni  阅读(3095)  评论(2编辑  收藏  举报

导航