SQL SERVER 查询当前数据库中的所有表的记录数

原贴位置:http://blog.csdn.net/minisunny/article/details/1791760

declare @sql varchar(8000),@count int,@step int

set nocount on

--@step越大运行速度越快,但如果太大会造成生成的sql字符串超出限制导致语句不完整出错

--建议为50

set @step = 50

if object_id(N'tempdb.db.#temp') is not null

drop table #temp

create table #temp (name sysname,count numeric(18))

if object_id(N'tempdb.db.#temp1') is not null

drop table #temp1

create table #temp1 (id int identity(1,1),name sysname)

insert into #temp1(name)

select name from sysobjects where xtype = 'u';

set @count = @@rowcount while @count>0

begin

set @sql = ''

select @sql = @sql + ' select ''' + name + ''',count(1) from ' + name + ' union'

from #temp1 where id > @count - @step and id <= @count

set @sql = left(@sql,len(@sql) - len('union'))

insert into #temp exec (@sql)

set @count = @count - @step

end

select count(count) 总表数,sum(count) 总记录数 from #temp

select * from #temp order by count,name

set nocount off

经过[测试],该方法可以通过,不过有时候@step的值需要手动设置一下,@step=50应该就可以满足大部分数据库的需要了.如果表名都比较短的话,可以设置@step=80或者100.

create table #(id int identity ,tblname varchar(50),num int)

declare @name varchar(30)

declare roy cursor for select name from sysobjects where xtype='U'

open roy

fetch next from roy into @name

while @@fetch_status=0

begin

declare @i int

declare @sql nvarchar(1000)

set @sql='select @n=count(1) from '+@name

exec sp_executesql @sql,N'@n int output',@i output

insert into # select @name,@I

fetch next from roy into @name

end

close roy

deallocate roy

select * from #

该方法用到了游标,如果数据库表很多的话速度可能会比较慢,但是该表不受表名长短影响,对所有数据库都适用.

最后一种方法是利用隐藏未公开的系统存储过程sp_MSforeachtable

CREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT)
EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(*) FROM ?'
SELECT TableName, RowCnt FROM #temp ORDER BY TableName
DROP TABLE #temp
    原文作者:马木木
    原文地址: https://www.jianshu.com/p/729d1b1594f7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞