Reputation: 83
What is the best way to compare data values in 2 different tables having same primary key in both tables?
Can anyone suggest the best method for this?
Upvotes: 0
Views: 2944
Reputation: 4816
Try with binary_checksum function, something like this:
declare @Table1 table (Id int identity(1,1), Param1 varchar(10), Param2 int)
declare @Table2 table (Id int identity(1,1), Param1 varchar(10), Param2 int)
insert into @Table1 (Param1, Param2) select 'A', 1
insert into @Table2 (Param1, Param2) select 'A', 1
select t1.*, t2.*
from @Table1 t1 full join @Table2 t2 on (t1.Id = t2.Id)
where binary_checksum(t1.Id, t1.Param1, t1.Param2) <> binary_checksum(t2.Id, t2.Param1, t2.Param2)
The query returns records, that are just in one table and not in another. The query also returns records, that are in both tables (using primary key), but the other columns are different.
Edit - what do you mean with different field names? If both tables have different fields, than off course they are different...
Upvotes: 0
Reputation: 238076
The usual way to compare two tables is a full outer join
, like:
select coalesce(t1.pk, t2.pk) as Key
, case
when t1.pk is null then 'Not found in Table1'
when t2.pk is null then 'Not found in Table2'
else 'Different'
end as Reason
from Table1 as t1
full outer join
Table2 as t2
on t1.pk = t2.pk
where t1.pl is null
or t2.pk1 is null
or t1.col1 <> t2.col1
or t1.col2 <> t2.col2
or t1.col3 <> t2.col3
...
Nullable columns require extra logic. Assuming that no row contains the value <<NULL>>
, you could:
or IsNull(t1.col4,'<<NULL>>') <> IsNull(t2.col4,'<<NULL>>')
Upvotes: 1
Reputation: 4827
If you want to compare data values, there are two levels;
you could have rows in one table that don't exist in another. Here you will need to do two left join queries with each of the tables on one side.
for the records that are in common, you will need to compare the fields one by one. There is unfortunately on easy way. The other way is to do a checksum across the whole row.
You can also buy sql redgate compare and data compare, which compares structure and data. You can try it with the trial software - its awesome.
http://www.red-gate.com/products/sql-development/sql-compare/
http://www.red-gate.com/products/sql-development/sql-data-compare/
Upvotes: 3