SQL SERVER 는 현재 데이터베이스 에 있 는 모든 표 의 기록 수 를 조회 합 니 다.
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 #
이 방법 은 커서 를 사 용 했 습 니 다. 데이터베이스 시트 가 많 으 면 속도 가 느 릴 수 있 지만 이 시 계 는 표 이름 의 장단 점 에 영향 을 받 지 않 고 모든 데이터 베이스 에 적 용 됩 니 다.
마지막 방법 은 공개 되 지 않 은 시스템 저장 과정 을 숨 기 는 spMSforeachtable
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