Compare Data Between Two Tables in SQL Server

I had explained the TableDiff in one of my previous posts.

In this post, let us see how to do a simple data comparison without using the TableDiff utility. Remember that this is only for small tables with less columns.

To create some sample data, let us take the Customers table of the Northwind database and create a duplicate of it


SELECT * INTO CustomersTemp FROM Customers




Now change some data in the Customers Temp table by using the following query


UPDATE CustomersTemp


SET City = 'Bern'


WHERE CUSTOMERID = 'ALFKI';


 


 


UPDATE CustomersTemp


SET Country = 'France'


WHERE CUSTOMERID = 'BOTTM';




It's now time to execute our query. I am comparing just 4 columns for changes. Remember as I said, use it on small tables with lesser columns:


SELECT table1.*, table2.*


FROM Customers AS table1


FULL JOIN CustomersTemp AS table2


ON table2.CustomerID = table1.CustomerID


WHERE


table1.CompanyName <> table2.CompanyName OR


table1.ContactName <> table2.ContactName OR


table1.Country <> table2.Country OR


table1.City <> table2.City




Running this query returns the two rows that do not match each other.

Know a better and simpler T-SQL that can do this? Share it here please!

No comments:

Post a Comment