Last active
August 29, 2015 14:00
-
-
Save dcs619/11405217 to your computer and use it in GitHub Desktop.
Compare rowcounts in two SQL tables with the same schema. Note: tables must have one or more primary keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DECLARE @OldDatabase varchar(50) | |
| DECLARE @NewDatabase varchar(50) | |
| SELECT @OldDatabase = '4-22-NS' | |
| SELECT @NewDatabase = '4-25-NS' | |
| ;WITH tableSchema AS ( | |
| SELECT k.* FROM information_schema.columns c | |
| INNER JOIN information_schema.key_column_usage k | |
| ON c.column_name = k.column_name | |
| AND c.table_name = k.table_name | |
| ), firstPK AS ( | |
| SELECT table_name, column_name as 'primarykey' | |
| FROM tableSchema | |
| WHERE ordinal_position = 1 | |
| ) | |
| SELECT DISTINCT 'SELECT ''' + c.table_name + ''' AS TableName, COUNT(1) AS RowCountDiff' + CHAR(13) + | |
| 'FROM [' + @NewDatabase + '].dbo.' + c.table_name + ' new ' + CHAR(13) + | |
| 'LEFT JOIN [' + @OldDatabase + '].dbo.' + c.table_name + ' old ' + CHAR(13) + | |
| STUFF(( | |
| SELECT ' AND new.' + c2.column_name + ' = old.' + c2.column_name | |
| FROM tableSchema c2 | |
| WHERE c2.TABLE_NAME = c.TABLE_NAME | |
| GROUP BY ' AND new.' + c2.column_name + ' = old.' + c2.column_name | |
| FOR XML PATH('') | |
| ), 1, 5, 'ON ' | |
| ) + CHAR(13) + 'WHERE old.' + f.primarykey + ' IS NULL;' + CHAR(13) | |
| FROM tableSchema c | |
| INNER JOIN firstPK f | |
| ON c.table_name = f.table_name | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment