Click here to Skip to main content
15,892,005 members
Articles / Database Development / SQL Server

Using SQL Server Metadata and Statistics to Build a Table Explorer Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
1 Oct 2012CPOL8 min read 22.4K   488   7  
Develops an analogy between database table and file directory information and argues that it could be very useful if it were possible to have a similar application to Windows Explorer for database tables. Demonstrates how to obtain the information from Sql Server system tables and dynamic management
/*
	Obtaining the table name, schema, row count and last update date
	user tables only 
*/
   select o.name             as [Name], 
          sc.name            as [Type], 
          s.row_count        as [Size], 
          u.last_user_update as [Modified]
 -- for table name and schema name
     from sys.objects o                                 
left join sys.schemas sc on sc.schema_id = o.schema_id  
 -- for the row count
left join (select object_id, sum(rows) as row_count     
             from sys.partitions                        
            where index_id < 2            -- only 0 or 1. Others will double-count
            group by object_id) s on o.object_id = s.object_id
 -- for last data update date
left join (select database_id, object_id, -- these two fields for object identification
                  max(last_user_update) as last_user_update   -- take the most recent update
                from sys.dm_db_index_usage_stats 
               where index_id < 2         -- only 0 or 1. Others are not necessary
            group by database_id,object_id
            ) u on u.object_id = o.object_id and u.database_id = DB_ID()
    -- Filter database objects to show user tables only
    where o.type = 'U'
    -- schema then table name seems a natural default ordering
    order by sc.name, o.name

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions