Compare tables on 2 db sqlserver

Posted on

Question :

I have SQL Server with 2 databases.

I want to compare them and see which tables are on the first database and not on the second database.

Only the names of tables matter, I don’t care about the values in those tables.

How can I do it?

Answer :

Tables in db1 that don’t exist in db2:

SELECT name FROM db1.sys.tables
EXCEPT
SELECT name FROM db2.sys.tables
ORDER BY name;

For more elaborate comparisons (like columns, indexes, and data types), don’t re-invent the wheel, as there are already tools that solve this problem.* For more info on this in general, see this blog post from ages ago.

Disclaimer: I work for SentryOne.

When I check differences between 2 tables I usually use the EXCEPT clause.

so you could use below to see all the differences.

--Rows in DB1 which are absent from DB2
select * from DATABASE1.dbo.Table1
except
select * from DATABASE2.dbo.Table1

--Rows in DB2 which are absent from DB1
select * from DATABASE2.dbo.Table1
except
select * from DATABASE1.dbo.Table1

Updated:

Try below SQL for comparing two different databases:

SELECT T.[name] AS [table_name], AC.[name] AS [column_name],  TY.[name] AS 
   system_data_type FROM    ***Database Name 1***.sys.[tables] AS T  
   INNER JOIN ***Database Name 1***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id]      
   INNER JOIN ***Database Name 1***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] 
   EXCEPT SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM    ***Database Name 2***.sys.[tables] AS T  
   INNER JOIN ***Database Name 2***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id]  
   INNER JOIN ***Database Name 2***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]

Leave a Reply

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