viernes, 28 de mayo de 2010

Record count on all the tables of a SQL Server database...

... using the count() function for each one:


declare @myTableName varchar(50)
declare @mySelect varchar(111)

declare CursorFoo cursor for
SELECT
so.name
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name


open CursorFoo

fetch next from CursorFoo into @myTableName


create table #totals (TableName varchar(100), RecordCount int)


while @@FETCH_STATUS = 0
begin

set @mySelect = 'select ''' + @myTableName + ''', count(*) from ' + @myTableName + ';'
insert into #totals exec (@mySelect);

fetch next from CursorFoo into @myTableName
end
select * from #totals
drop table #totals
close CursorFoo
deallocate CursorFoo

2 comentarios:

YoLoL dijo...

Bienvenido de vuelta a la blogosfera, hacía rato que no posteabas =)

infomar dijo...

Gracias, Andrés.
Es que estaba escribiendo en el otro blog.
Gusto en saludarte.