Home > Tips N Tricks > Database Summary

Database Summary


Problem: View sample data for each table in a database.

Solution: Many times we may come across some situations especially when looking for any information on a big database or when exploring tables on it, where we may feel to get some easy methods to get the whole thing instead of browsing each table one by one either by T-SQL statements or by UI of SSMS.

So, here is a tweak which gives you the whole picture of the database with relevant information i.e. Table Name, Total No. of Records and some sample records (usually top 5).


The below procedure uses sysobjects and sysindexes to get the information that we want: 

-- =============================================
-- Author:       <Arun Kumar Mallick>
-- Description: <List all table names, Total Row count for each table and sample data from each table in a given database>
-- =============================================
/*
 
EXEC dbo.[DatabaseSummary]
 
*/
ALTER PROCEDURE [dbo].[DatabaseSummary]
	AS
BEGIN
	SET NOCOUNT ON;
 
    DECLARE @tablename varchar(200)
	DECLARE @totalRowCount int
	DECLARE @SQLstr nvarchar(500)
 
	DECLARE tabSumCur CURSOR
	FOR
	Select sysobjects.name, rowcnt from sysindexes inner join sysobjects
	on sysindexes.id = sysobjects.id and sysobjects.xtype = 'U' and (indid = 0 or indid = 1) order by sysobjects.name
 
	OPEN tabSumCur
	FETCH NEXT from tabSumCur INTO @tablename, @totalRowCount
 
	while @@FETCH_STATUS = 0
	BEGIN
		--SET @SQLstr = 'select top 4 ''' + @tablename +''' as TableName, * from ' + @tablename
		SELECT @tablename as TableName, @totalRowCount as TotalRowCount
		SET @SQLstr = 'select top 4 * from ' + @tablename
		EXEC sp_executesql @SQLStr
 
		FETCH NEXT from tabSumCur INTO @tablename, @totalRowCount
	END
 
	CLOSE tabSumCur
	DEALLOCATE tabSumCur
 
END


Categories: Tips N Tricks
  1. No comments yet.
  1. No trackbacks yet.