Question

i have a task to cleanup the database from useless records. in the planning, first i have to check what are the tables that holds the most number of records. i know i can check them one by one manually, but the table list is too long and am thinking it's not too wise to run through them manually before checking if there is any automatic query that can do the job. manually, i can query each table using this query:

select count(*) from <table_name>

even using sysobjects, i could not find the current Number Of Records

select * from sysobjects s where type='U' and name = '<table_name>'

anybody has an idea?

Was it helpful?

Solution

An approximation for the number of rows in each table is kept as part of index statistics, and is stored in the yourDB..systabstats Assuming you run update statistics on a regular basis, here's how you can get the information.

SELECT o.name, t.rowcnt
  FROM sysobjects o, systabstats t
WHERE o.id = t.id
  AND t.rowcnt > 0            --ignore 0 row entries
  AND o.name not like "sys%"  --exclude system tables
ORDER BY t.rowcnt DESC

OTHER TIPS

This works in T-SQL. Not sure if it will work in Sybase...

    CREATE TABLE #RecCounts (TableName varchar(100), RecCount int)

    SELECT object_id INTO #Processed FROM sys.tables WHERE name = '(no such table)'

    DECLARE @TableId int, @TableName varchar(255), @TableSchema varchar(100), @CountSQL varchar(255)

    SELECT @TableId = MIN(object_id) FROM sys.tables WHERE type = 'U'
    AND object_id NOT IN (SELECT object_id FROM #Processed)

    SET @TableId = ISNULL(@TableId, -1)

    WHILE @TableId > -1 BEGIN

        PRINT @TableId

        SELECT @TableName = name FROM sys.tables WHERE type = 'U' AND object_id = @TableId

        SELECT @TableSchema = s.name, @TableName = t.name
            FROM sys.Tables t
            INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
        WHERE t.object_id = @TableId



        SET @CountSQL = 'DECLARE @RecCount int
                            SELECT @RecCount = COUNT(*) FROM ' + @TableSchema + '.' + @TableName + '
                            INSERT INTO #RecCounts (TableName, RecCount) VALUES (''' + @TableName + ''', @RecCount)'

        PRINT @CountSQL
        EXEC(@CountSQL)

        INSERT INTO #Processed (object_id) VALUES(@TableId)

        SELECT @TableId = MIN(object_id) FROM sys.tables WHERE type = 'U' 
            AND object_id NOT IN (SELECT object_id FROM #Processed)

    END


    SELECT * FROM #RecCounts
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top