|
|
Question : Loop over all user tables, return rowcount for each (Sybase ASE15)
|
|
I need to create a procedure which, when called, will return for every user table in a specific database, the tablename & row count.
I tried doing something with: select distinct o.name, t.rowcnt from systabstats t, sysobjects o where t.id = o.id and o.type = 'U' order by o.name go
But the result did not give me the correct # of rows. So I think I need something which will loop over all tables doing count(*) and returning tablename & rownumber. But this I cannot figure out. And, of course, I need it by this evening.
Regards, Cap
|
Answer : Loop over all user tables, return rowcount for each (Sybase ASE15)
|
|
The only way to do this is to open up a cursor on the sysobjects table and do a SELECT COUNT(*) FROM TableName as dynamic SQL.
Something like....
CREATE PROC sp_alltables_rowcount AS BEGIN SET NOCOUNT ON DECLARE @ROWCOUNT_CMD VARCHAR(255), @TABNAME VARCHAR(32), @US_MSG VARCHAR(128), @DB_MSG VARCHAR(128) DECLARE TABLIST CURSOR FOR SELECT 'select ''' + name + ''', count(*) from ' + name AS ROWCOUNT_CMD, name AS TABNAME FROM sysobjects WHERE type = 'U'
SET @DB_MSG = 'STARTING -- Rowcounts for database: '+ db_name()+' at '+ convert(varchar,getdate()) PRINT @DB_MSG
OPEN TABLIST FETCH TABLIST INTO @ROWCOUNT_CMD, @TABNAME WHILE @@sqlstatus = 0 BEGIN EXEC (@ROWCOUNT_CMD) FETCH TABLIST INTO @ROWCOUNT_CMD, @TABNAME END CLOSE TABLIST SET @DB_MSG = 'FINISHED -- Rowcounts for database: '+ db_name()+' at '+ convert(varchar,getdate()) PRINT @DB_MSG
RETURN END
Be sure to put this procedure in the SYBSYSTEMPROCS database. You can then call it from any database and only have to maintain the code once.
BTW, I tested this on 12.5.1, not v15 so there is a very slight chance you may have to adjust the select statement in the cursor declaration.
Regards, Bill
|
|
|
|
|