Home > Back-end >  How do I only import unique records into a table from another table?
How do I only import unique records into a table from another table?

Time:12-17

I am trying to update a table in SQL Server. Table is called table1 with columns(code, desc). I want to update table1 with unique records from table2(code, desc). table2 is a copy of table1 but it contains records that are not present in table1.

EDIT 1: table1 consists of all the records in our ERP when exported in July, table2 consists of all the records in our ERP when exported in November (including records added after July which are the records that I want to add to table1)

CodePudding user response:

Sounds like you want an INSERT

Something like this should work:

INSERT INTO table1 (code, desc)
SELECT t2.code, t2.desc
FROM table2 t2
LEFT JOIN table1 t1 on t2.code = t1.code and t1.desc = t2.desc
WHERE t1.code is null --Ignore records that already exist in table1

... Adjust join clause accordingly.

CodePudding user response:

To update table1.desc with values from matching rows in table2 simply do:

update t1 set 
  t1.desc = t2.desc
from table1 t1
join table2 t2 on t2.code = t1.code;

If however you want to insert rows into table1 that only exist in table2 (it's not exactly clear if that's the case) you can use not exists

insert into table1 (code, desc)
select code, desc
from table2 t2
where not exists (select * from table1 t1 where t1.code = t2.code);
  • Related