Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Evite duplicatas na consulta INSERT INTO SELECT no SQL Server


Usando NOT EXISTS :
INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE NOT EXISTS(SELECT id
                    FROM TABLE_2 t2
                   WHERE t2.id = t1.id)

Usando NOT IN :
INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE t1.id NOT IN (SELECT id
                       FROM TABLE_2)

Usando LEFT JOIN/IS NULL :
INSERT INTO TABLE_2
  (id, name)
   SELECT t1.id,
          t1.name
     FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
    WHERE t2.id IS NULL

Das três opções, o LEFT JOIN/IS NULL é menos eficiente. Veja este link para mais detalhes.