NOT IN插入的性能增强

时间:2013-07-02 06:30:10

标签: sql sql-server insert

我在MS SQL存储过程中有以下插入:

insert into Status_Table(Field1, Field2, Field3, Status_ID, Status_ID2)
select a.Field1 , a.Field2 , a.Field3 , a.Status_ID , a.Status_ID2 
  from ##StatusTempTable as a  
  where a.Status_ID+a.Status_ID2 not in(select Status_ID+Status_ID2 from Status_Table)

在我执行Insert之前,我将检查是否存在具有相同Status_ID和Status_ID2的任何行。表Status_Table包含超过3 Mio行,Insert变得非常长。是否有增加Peroformance的替代方案?

2 个答案:

答案 0 :(得分:2)

尝试使用NOT EXISTS代替NOT IN

insert into Status_Table(Field1, Field2, Field3, Status_ID, Status_ID2)
select a.Field1 , a.Field2 , a.Field3 , a.Status_ID , a.Status_ID2 
  from ##StatusTempTable as a  
  where not exists(select * from Status_Table s where s.Status_ID = a.Status_ID AND s.Status_ID2 = s.Status_ID2 )

答案 1 :(得分:0)

在SQLServer2008 +中,您也可以使用MERGE语句

MERGE dbo.Status_Table AS target
USING dbo.##StatusTempTable AS source
ON (target.Status_ID = source.Status_ID AND target.Status_ID2 = source.Status_ID2)
WHEN NOT MATCHED
  THEN INSERT(Field1, Field2, Field3, Status_ID, Status_ID2)
       VALUES(
              source.Field1,
              source.Field2,
              source.Field3,
              source.Status_ID,
              source.Status_ID2
              );