3

我在 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)

在进行插入之前,我将检查是否存在具有相同 Status_ID 和 Status_ID2 的行。表 Status_Table 包含超过 3 个 Mio 行,插入变得很长。是否有其他方法可以提高性能?

4

2 回答 2

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 )
于 2013-07-02T06:36:14.910 回答
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
              );
于 2013-07-02T14:21:33.370 回答