Hi There,

Thank You for visiting my blog. I have moved this blog to a new address http://dattatreysindol.com/. Please visit the blog at new address and re-point your feeds to the new address to continue to receive regular updates.
Thanks,
Dattatrey Sindol (Datta)

Datta's Ramblings on Business Intelligence 'N' Life

Get the Record Count for all the Tables in a Database in SQL Server

» 19 Feb 2010 | | |

Often we take the COUNT of records in a table or many of the times all the tables in a database. We might need to get the COUNT of records in all the tables especially for validation purposes.

For instance when you are loading the data into your Staging Database in an incremental fashion, you need to do few checks to make sure that the incremental logic is working fine. As part of this, one of the most basic checks is to first get the COUNT of records from all the tables in Source & Staging Databases and compare the COUNTs.

Here is a very simple way to get the COUNT of records from all the tables in a database. Run the following query in the database in which you need to get the COUNTs of all the tables.
DECLARE @QueryString NVARCHAR(MAX)

SELECT @QueryString = COALESCE(@QueryString + ' UNION ALL ','') + 'SELECT ' + '''' + TABLE_SCHEMA + '.' + TABLE_NAME + '''' + ' AS TableName, COUNT(1) AS RecordCount FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_SCHEMA, TABLE_NAME

EXEC Sp_executesql @QueryString

When you run the above query in AdventureWorksDW database then the results will be as shown below (Tables/Counts might slightly vary depending on the version of AdventureWorksDW).



Readers Feedback:
Did you like this article?
If Yes, then please share it:
Did you like my blog?
If Yes, then please help spread the word by sharing this blog with your colleagues, friends, & anyone else in the MSBI Space: Like us on Facebook , Follow us on Twitter .

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

About the Author

Dattatrey Sindol is a BI Tech Lead & a passionate SQL Server Developer in a leading IT company.  read more »
Connect with Datta:

Thank You Visitors!

Hi There, Thanks for Visiting my Blog. Please feel free to leave your Comments/Suggestions about any of my Articles/My Blog.

Do Not Copy this Blog's Content !

Protected by Copyscape Online Copyright Checker