如何通过选择插入时插入表格之前如何检查重复项

Pra*_*bhu 9 sql t-sql sql-server sql-server-2005 sql-server-2008

如何通过选择插入时插入表格之前如何检查重复项:

insert into table1
select col1, col2 
from table2
Run Code Online (Sandbox Code Playgroud)

我需要检查table1是否已经有一行table1.col1.value = table2.col1.value,如果是,则从插入中排除该行.

Con*_*rix 17

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 
Run Code Online (Sandbox Code Playgroud)

替代使用除外

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 
Run Code Online (Sandbox Code Playgroud)

替代使用不存在

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)
Run Code Online (Sandbox Code Playgroud)

  • @Prabhu - "LEFT JOIN ... IS NULL"是一种检查现有值并且只插入它们不存在的常用方法."NULL"表示在`col1`中没有具有该值的现有行. (2认同)