sql >> Base de Datos >  >> RDS >> Sqlserver

Evite duplicados en la consulta INSERT INTO SELECT en 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

De las tres opciones, la LEFT JOIN/IS NULL es menos eficiente. Consulte este enlace para obtener más detalles.