简体   繁体   中英

How do i insert a value in 1 table if it doesnt exist in another

I have two near identical tables and want to insert the values that exist in the 1st but not in the 2nd into the 2nd.

I do not care about updating the 1st table with missing values in the 2nd, just vice versa.

I tried this select as a test but it returned nothing even for values i know are missing

select * from table1 where Not Exists(Select * from table2)

Assuming you have a field to join both tables together, something like this would work:

INSERT INTO table2 (id, col1)
SELECT id, col1
FROM table1
WHERE NOT EXISTS (
    SELECT 1
    FROM table2 
    WHERE table1.id = table2.id)

You can also accomplish the same thing with NOT IN and OUTER JOIN , but you'd still need the matching criteria from both tables.

You can do this in the general sense with an INSERT statement like the following:

INSERT INTO TABLE2(Col1, Col2, ...)
  SELECT Col1, Col2, ....
  FROM TABLE1 t1
  WHERE NOT EXISTS
  (SELECT 1 FROM Table2 t2 WHERE t2.Criteria = t1.Criteria);

Similarly, the reverse can be done for TABLE2 => TABLE1 .

You'll need to specify which columns make up the common criterion. Be wary that if the 2 tables are inserted into independently of eachother (as the requirement suggests), that autogenerated columns like Guids or IDENTITY will differ in the 2 tables and are not suitable as the join criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM