sql >> Database >  >> RDS >> Sqlserver

Hoe kan ik controleren op duplicaten voordat ik deze in een tabel invoeg bij het invoegen met select

INSERT INTO table1 
SELECT t2.col1, 
       t2.col2 
FROM   table2 t2 
       LEFT JOIN table1 t1 
         ON t2.col1 = t1.col1 
            AND t2.col2 = t1.col2 
WHERE  t1.col1 IS NULL 

Alternatief gebruik behalve

INSERT INTO @table2 
SELECT col1, 
       col2 
FROM   table1 
EXCEPT 
SELECT t1.col1, 
       t1.col2 
FROM   table1 t1 
       INNER JOIN table2 t2 
         ON t1.col1 = t2.col1 
            AND t1.col2 = t2.col2 

Alternatief met Not Exists

INSERT INTO table2 
SELECT col1,col2 
FROM table1 t1
WHERE
NOT EXISTS( SELECT 1
    FROM table2 t2
    WHERE t1.col1 = t2.col1
          AND t1.col2 = t2.col2)


  1. 1054 - Onbekende kolom 'apa_calda' in 'where-clausule'

  2. Postgres-vensterfunctiekolom met Rails

  3. MySQL:groeperen op en meerdere velden tellen

  4. Hoe APPROX_COUNT_DISTINCT() werkt in SQL Server