SQL Server Management Studio - Finding all non empty tables

后端 未结 6 2104
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 02:00

Is there a way for SQL Server Management Studio Express How to list all the non empty tables? I have over 100 tables to go through and check for data.

6条回答
  •  星月不相逢
    2020-12-16 02:14

    Lets say Tables can be of two types.

    1. Clustered Table ( Tables having a Clustered Index )
    2. Heap Tables ( Tables not having a Clustered Index )

    All tables in SQL Server are divided into partitions. So that all table will have atleast one partition .

    In sys.partitions, there exists one row for each partition of all tables.

    These rows in sys.partitions contains information about number of rows in that partition of the corresponding table.

    Since all tables in SQL Server contain aleast one partition, we can get the information about number of rows in a table from sys.partitions.

    SELECT
            OBJECT_NAME(T.OBJECT_ID) AS TABLE_NAME,
            SUM(P.ROWS)  AS TOTAL_ROWS
    FROM
            SYS.TABLES T
    INNER JOIN 
            SYS.PARTITIONS P 
            ON T.OBJECT_ID = P.OBJECT_ID
    WHERE 
            P.INDEX_ID IN (0,1)
    GROUP BY 
            T.OBJECT_ID
    HAVING 
            SUM(P.ROWS) > 0
    

    While taking sum of rows in different partitions, we are considering index_id (0,1)

    • index_id = 0 for Heap
    • index_id = 1 for Clustered index
    • index_id > 1 are for nonclustered index.

    A table can have either one clustered index or none.

    But that is not the case with nonclustered index. A table can have multiple nonclustered indexes. So we cannot use those index_id while summing rows.

    • Heap Tables will be having index_id = 0
    • Clustered Tables will be having index_id = 1

提交回复
热议问题