Get count of multiple tables using T-SQL – SQL Server

I was asked by my coworker get row count of tables with a particular column. So I came up with this little script to get it quickly using T-SQL.

DECLARE @tableName VARCHAR(255)
DECLARE @count smallint
DECLARE @stmt NVARCHAR(4000);

##Create insert statement into temp.

SET @stmt = 'INSERT INTO #tmpTable (tableNames, recCount)
SELECT ''** tableName **'', count(*) from ** tableName ** WHERE 1=1 and
= ''value''';

##Create temp table

CREATE table #tmpTable(
tableNames VARCHAR(255),
recCount smallint
)

##Declare CURSOR for select statement from sys.columns

DECLARE db_cursor CURSOR FOR
select distinct OBJECT_NAME(object_id) from sys.columns
where 1=1
and name = '
'

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tableName

##Use while loop to insert record count in temp table.

WHILE @@FETCH_STATUS = 0

BEGIN

SET @stmt = REPLACE(@stmt, '** tableName **', @tableName);

EXEC sp_executesql @stmt;

SET @stmt = 'INSERT INTO #tmpTable (tableNames, recCount)
SELECT ''** tableName **'', count(*) from ** tableName ** WHERE 1=1 and
= ''value''';

FETCH NEXT FROM db_cursor INTO @tableName

END

Close db_cursor
DEALLOCATE db_cursor

##Get all the tables with count

select * from #tmpTable

#Drop temp table.

drop table #tmpTable

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>