`
sherrysky
  • 浏览: 87091 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

sql server 查询所有表的记录数

阅读更多
--方法1,利用系统函数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
--方法2,自己写函数,有问题,因为数据库用户表名USER,可能和系统表冲突,修改后可以正常运行,结果正确
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
--drop table #temp
--方法3,自己写函数,有问题,因为数据库用户表名USER,可能和系统表冲突,修改后可以正常运行,结果正确
create table #(id int identity ,tblname varchar(50),num int)

declare @name varchar(50)

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(4000)

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 #
--drop table #
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics