-2

Hello I'm having trouble figuring out how to insert rows that are not duplicates from one table to another, I have in mind something like this

INSERT INTO Table1
       SELECT id, name, lastname FROM Table2
              WHERE id.Table1 != id.Table2 
              AND name.Table1 != name.Table2 
              AND lastname.Table1 != lastname.Table2

How to write that condition that specifies not to insert if it already exists?

EDIT: I forgot to mention that I needed to match only certain columns since the tables contain identity 1,1 my solution is as follows:

    MERGE Table1 as t1
    USING (SELECT name, lastname FROM Table2) AS t2 (name, lastname) 
    ON t1.[name] = t2.[name] AND t1.[lastname] = t2.[lastname] 
    WHEN NOT MATCHED 
    THEN
    INSERT (name, lastname) VALUES (t2.[name], t2.[lastname]);

Of course this is just an example I'm using a lot more columns and data

edit: not a duplicate since the solutions presented match the entire table

2 Answers2

5

One way to approach this is to use the except operator:

INSERT INTO Table1
SELECT id, name, lastname FROM Table2
EXCEPT
SELECT id, name, lastname FROM Table1
Mureinik
  • 252,575
  • 45
  • 248
  • 283
  • Thank you for your reply, I forgot to mention that I needed to match certain columns but not all, I found the solution with merge – Roberto Torres Oct 04 '17 at 15:58
1

You may use NOT EXISTS. Please be aware that table name is always before attribute name.

 INSERT INTO Table1
   SELECT id, name, lastname 
   FROM Table2
   WHERE NOT EXISTS (
             SELECT * 
             FROM Table1 
             WHERE Table1.id = Table2.id AND 
                   Table1.name = Table2.name AND 
                   Table1.lastname = Table2.lastname
           )
Radim Bača
  • 10,193
  • 1
  • 15
  • 31