通过具有大量记录来排序的查询表

时间:2014-02-06 15:07:48

标签: sql sybase sybase-ase

我有一项任务是从无用的记录中清理数据库。在规划中,首先我必须检查拥有最多记录数的表是什么。我知道我可以手动逐一检查它们,但是表格列表太长了,我认为在检查是否有任何可以完成工作的自动查询之前手动运行它们并不太明智。 我可以手动查询每个表:

select count(*) from <table_name>

即使使用sysobjects,我也找不到当前的记录数

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

有人有想法吗?

2 个答案:

答案 0 :(得分:2)

每个表中行数的近似值作为索引统计信息的一部分保存,并存储在yourDB..systabstats假设您定期运行update statistics,以下是如何获取信息。

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

答案 1 :(得分:0)

这适用于T-SQL。不确定它是否适用于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