Friday 5 July 2019

Retrieving table records count from the SQL database

The steps to be followed as mentioned below:

1. Open SQL Server Management Studio (SSMS)

2. Connect to the database server (instance))

3. Go to database, Click “New Query” from SSMS menu tool bar


4. Copy the following SQL Query and Paste it to the “New Query” Window


SET NOCOUNT ON;
DECLARE @LastTableName VARCHAR(128)
SET @LastTableName = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME DESC)

SELECT 'SELECT ''' +  TABLE_NAME + ''' AS TableName, COUNT(1) AS  RecordCount FROM ' + TABLE_NAME +
CASE WHEN TABLE_NAME = @LastTableName THEN '' ELSE CHAR(13) +'UNION ALL ' END FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME
SET NOCOUNT OFF;


5. Click “Result to Text” button from SSMS menu tool bar(Previous button of “Result to Grid” button)

6. Execute the SQL query which you have pasted in the “New Query” Window

7. You will get the SQL Query for counting the table records of selected database in the Result section

8. Copy the full SQL query script which is in the Result section, paste it to the “New Query” Window and Execute it

9. You get the Record count for each table of selected database







No comments:

Post a Comment