Friday, 21 December 2018

Compare Row Counts in Tables From Two Different Databases With the Same Schema


USE [OldDBName]
CREATE TABLE #counts
(
table_name varchar(255),
row_count int
)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'

USE [NewDBName]
CREATE TABLE #counts_2
(
table_name varchar(255),
row_count int
)

EXEC sp_MSForEachTable @command1='INSERT #counts_2 (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'

SELECT a.Table_Name,
a.row_count as [Counts from OLD],
b.row_count as [Counts from New],
a.row_count - b.row_count as [Difference]
FROM #counts a
inner join #counts_2 b on a.table_name = b.table_name
where a.row_count = b.row_count
ORDER BY a.table_name, a.row_count DESC

No comments:

Post a Comment