Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Management Studio - Finding all non empty tables

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.

like image 457
Peter Sun Avatar asked Jul 19 '13 14:07

Peter Sun


People also ask

How do I find non empty tables in database?

mysql> select table_type, table_name from information_schema. tables −> where table_rows >= 1; Above, we have considered only the table that have 1 or more than 1 rows i.e. non-empty table.

How do I get a list of tables in SSMS?

First, enable Object Explorer Details going to View > Object Explorer Details or by pressing F7 buton. Now, select Tables element in your database in Object Explorer. List of tables with details will show in in the right pane in Object Explorer Details tab.


1 Answers

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
like image 159
jophab Avatar answered Sep 29 '22 11:09

jophab