February 18, 2009

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'




UPDATE CustomersTemp

SET Country = 'France'


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


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!

Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal



0 Responses to "Compare Data Between Two Tables in SQL Server"

Copyright © 2009-2016 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions