Technical Article

3 ways to find out rowcount of all tables in a database

,

==================Method 1)To find out the rows of each table in the database======

/*

TIP :- BEFORE EXECUTING I WILL RECOMMEND TO RUN UPDATEUSAGE ON THE DATABASE TO GET THE EXACT ROWCOUNT OF THE TABLES.

Purpose of the script :- To find out no. of rows for all the tables for a particular database.It will also give you the

run date and time of script.

STEPS :- Just copy this script in a query analyzer, it will automatically,

1) Create a temoporary table named #spaceused

2) Display the DATE and TIME of script run,database name,table name and no. of rows for all the tables for particular database.

3) drop the table #spaceused

*/

create table #spaceused (dbname varchar(50), name varchar(100) ,rows int,reserved varchar(50),data varchar(10),
index_size varchar(10),unused varchar(10),rep_gen_dt datetime)

declare spaceused_cur cursor for select name from sysobjects where xtype='U'

declare @name varchar(100)
open spaceused_cur

fetch next from spaceused_cur into @name

insert into #spaceused(name,rows,reserved,data,index_size,unused) exec sp_spaceused @name

WHILE @@FETCH_STATUS = 0
BEGIN
fetch next from spaceused_cur into @name
if @@FETCH_STATUS = -1
break
insert into #spaceused(name,rows,reserved,data,index_size,unused) exec sp_spaceused @name
END

update #spaceused set dbname = db_name() where dbname is NULL
update #spaceused set rep_gen_dt = getdate() where rep_gen_dt is NULL
select rep_gen_dt,dbname,name,rows from #spaceused order by name
close spaceused_cur
deallocate spaceused_cur
drop table #spaceused

================ END OF Method 1) ===============================

===========Method 2)To find out the rows of each table in the database================

select so.name,si.rowcnt from sysobjects so,sysindexes si
where so.id = si.id and so.type ='u'
and si.indid in (0,1)
order by so.name

=================== END OF Method 2) ===================================

=============Method 3)To find out the rows of each table in the database====================

NOTE :- copy the output generated by following query, paste it in the query analyzer and delete the last "union" keyword then execute the copied script)

It may take some time than previous 2 scripts.

select 'select ''['+name+']'' as "TableName", count(*) as "Row Count" from ['+name+'] union'from sysobjects where xtype='u' order by name

===================== END OF Method 3) ===============================

  

Rate

4.5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

4.5 (2)

You rated this post out of 5. Change rating