Assume there are two tables: Remote_table and My_table.
Remote_table has 6 columns:
PROJECT JOB_TYPE MONTH YEAR** HOURS IS_DELETED
134393 70 1 2013 30 0
134393 70 2 2013 50 0
134393 70 3 2013 80 0
134393 70 10 2012 10 0
134393 70 11 2012 0 0
134393 70 12 2012 15 0
My_table is a copy of remote_table.
I tried to copy only the new records from the remote_table by this query:
SELECT *
FROM [remote_DB].[LudanProjectManager].[dbo].Remote_table
EXCEPT
SELECT *
FROM My_table
It works OK but I get a duplicate primary key exception when changes have been made on the remote_table on the hours column.
Can anyone think of a way to copy only the new records from remote_table and if changes has been made on old records, to identify them and update the my_table to correspond?
Since you are using SQL Server 2008, you can use
MERGE:Note that:
ONclause, may be you need to restrict the matching rows using extra conditions, TGT.Year = SRC.TGT, ..or just matched on thePROJECTfield only usingON TGT.PROJECT = SRC.PROJECT.MEREGEstatement with a semicolon. It is mandatory.INSERTstatement there was noINTO TableNamebecause the name of the target table is already defined in theMERGEclause.