question

tiwaryrohit143 avatar image
tiwaryrohit143 asked

I have to find row count of all tables in a database based on a distinct column value in respective table.

I have to find row count of all tables in a database based on a distinct column value in respective table.

Example i have 10 table having 1 column common in them . so i want to find row count for different values of this common column in each table.

sqlt-sqlsql server 2012tablespartition
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Jon Crawford avatar image
Jon Crawford answered

something like this:

DECLARE @SQL nvarchar(4000);

WITH tableName AS (

SELECT [value] ='myTable1'UNIONALL

SELECT'myTable2'UNIONALL

SELECT'myTable3'UNIONALL

SELECT'myTable4'UNIONALL

SELECT'myTable5'UNIONALL

SELECT'myTable6'UNIONALL

SELECT'myTable7'UNIONALL

SELECT'myTable8'UNIONALL

SELECT'myTable9'UNIONALL

SELECT'myTable10'

)

SELECT @SQL =COALESCE(@SQL,'')+N'SELECT

[tableName] = '''+tableName.value+''',

[records] = COUNT(*),

[yourField]

FROM [dbo].['+tableName.value+']

WHERE 1=1 --replace with condition here

GROUP BY [yourField]

UNION

'

FROM tableName;

--chop off the last union and add an order by

SET @SQL =SUBSTRING(@SQL,1,LEN(@SQL)-7)+N'ORDER BY tableName,records';

--this is just to verify your code, you may have to adjust the substring above to chop out the last UNION correctly

SELECT @SQL;

--uncomment this to run the query once you're happy with it

--EXECUTE sp_executesql @SQL;

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.