Compare Two SQL Server Databases using Tsql
I’m glad to inform that today I’m going to release my next phase of TsqlTools is SQLCOMPARE. I was in a point to compare two databases which are on two different servers, I have checked many websites and blogs, but unfortunately, I didn’t find any useful T-SQL query for that. But there is so many good software available to compare the databases. Red-Gate is one of my favorite tool for comparison.
So I have prepared 3 Tsql scripts to compare all databases objects between two SQL servers.
1. Tables and Objects #
- CHECK_CONSTRAINT
- DEFAULT_CONSTRAINT
- FOREIGN_KEY_CONSTRAINT
- PRIMARY_KEY_CONSTRAINT
- SECURITY_POLICY
- SEQUENCE_OBJECT
- SQL_INLINE_TABLE_VALUED_FUNCTION
- SQL_SCALAR_FUNCTION
- SQL_STORED_PROCEDURE
- SQL_TABLE_VALUED_FUNCTION
- SQL_TRIGGER
- TYPE_TABLE
- UNIQUE_CONSTRAINT
- USER_TABLE
- VIEW
2. Index Compare #
This will compare Indices from both servers and list out missing indices on each server.
3. Row Count #
This is very straightforward, Just get the row count of all database’s tables from both server and show the difference.
How to Run this query? #
You can use a centralized Server and create LinkedServers for Source and Target DB servers, or Create a LinkedServer for Target server on SourceDB server, then run the query on Source DB server.