仅在记录不存在时插入表格

时间:2017-09-11 06:14:48

标签: sql-server

Insert into t1(col1,col2,col3)    
select   
t2.col1,
t2.col2,
t3.col2

from 
table2 t2 left outer join
table3 t3     
on t2.col1=t3.col1

这是我的代码的基础知识。如何检查插入的数据是否已经存在?

2 个答案:

答案 0 :(得分:0)

您可以使用

 if(not exists (select col1 from t1 where col1 in(select   
t2.col1 
from 
table2 t2 left outer join
table3 t3     
on t2.col1=t3.col1)))

   Begin
Insert into t1(col1,col2,col3)    
select   
t2.col1,
t2.col2,
t3.col2

from 
table2 t2 left outer join
table3 t3     
on t2.col1=t3.col1
   end

ps这里只检查col1数据,你可以添加col2和col3

答案 1 :(得分:0)

使用SQL EXISTS运算符

 INSERT  INTO t1
        ( col1 ,
          col2 ,
          col3
        )
        SELECT  t2.col1 ,
                t2.col2 ,
                t3.col2
        FROM    table2 t2
                LEFT OUTER JOIN table3 t3 ON t2.col1 = t3.col1
        WHERE   NOT EXISTS ( SELECT 1
                             FROM   T1
                             WHERE  t1.col1 = t2.col1
                                    AND t1.col2 = t2.col2
                                    AND t1.col3 = t3.col2 )
相关问题