Search code examples
sqlsql-server-2017

SQL Server : joining 2 tables where each row has unique PKEY value


I am attempting to join 2 tables with an equivalent amount of columns and where each column is named the same. Tb1 is an MS Access table that I have imported to SQL Server. Tb2 is a table that is updated from tb1 quarterly and is used to generate reports.

I have gone into design view and ensured that all column datatypes are the same and have the same names. Likewise, every row in each table is assigned a unique integer value in a column named PKEY.

What I would like to do is add all new entries present in tb1 (the MS Access table) to the existing tb2. I believe this can be done by writing a query that loads all unique pkeys found in tb1 (AKA load all keys that are NOT found in both tables, only load unique keys belonging to rows in the access table) and then appending these entries into Tb2.

Not really sure where to start when writing this query, I tried something like:

SELECT * 
FROM tb1 
WHERE PKEY <> Tb2.PKEY

Any help would be greatly appreciated. Thanks!


Solution

  • I would recommend not exists:

    select tb1.*
    from tb1
    where not exists (select 1 from tb2 where tb2.pkey = tb1.pkey);
    

    You can put an insert before this to insert the rows into the second table.