Search code examples
sql-server-2008-express

Compare rows in different table having same columns


I have 2 tables tbl_A and tbl_A_temp. Both the table have the same schema. their primary key differ since they are identity columns. Is there a way i can compare the two rows in these two table and get to know if they differ.I will be inserting data from tbl_A_temp to tbl_A, i need this compare just to make sure that I am not inserting any duplicate data in the main tables.

Regards, Amit


Solution

  • I think this should work for you. Basically, since you don't have a primary key to join on, you'll need to perform a LEFT JOIN on all your other fields. If any are different, then the NULL check will be true:

    SELECT t.*
    FROM tbl_A_temp t
       LEFT JOIN tbl_A a ON 
          t.field1=a.field1 AND t.field2=a.field2 AND ...
    WHERE a.field1 IS NULL
    

    I've also seen others use CHECKSUM, but have run into issues myself with it returning false positives.