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 where count>0 order by count,name set nocount off