工作过程中,如果一个数据库的表比较多,手工编写统计脚本就会比较繁琐,于是摸索出自动生成各表统计数据量脚本的通用方法,直接上代码:
create table #t ( ID int identity(1,1), name nvarchar(200) ) insert into #t(name) select s.name + '.' + t.name as TableName from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id declare @iCount int = (select count(*) from #t), @i int = 1, @s nvarchar(max) = '', @name nvarchar(200) = '' while @i <= @iCount begin select @name = (select name from #t where ID = @i) if @i < @iCount select @s = @s + 'select ''' + @name + ''' as TableName, count(*) as Num from ' + @name + ' union ' else if @i = @iCount select @s = @s + 'select ''' + @name + ''' as TableName, count(*) as Num from ' + @name select @i = @i + 1 end select @s = 'select * from (' + @s + ') a order by Num desc' --print @s exec (@s) drop table #t
以在ReportServer数据库中运行这个脚本为例,运行结果如下图(表名、数据量):
后记:
以上是本人在实际工作中遇到的sql server编写通用脚本自动统计各表数据量的一劳永逸解决办法,特此分享一下,希望对遇到同样问题的朋友有所帮助。如果帮助到了你,欢迎给我打赏支持一下哦。