2012-05-29 80 views
2

有没有办法在SQL Server 2005中批量插入?类似于2008年的MERGE将是完美的。我有一个表作为临时工作区工作,需要在会话完成时与主表一致。在2008年,合并对此会有很大的帮助,但我见过的2005年唯一的方法是针对单个的upserts,而不是批量。想法?Bulk Upsert SQL Server 2005

回答

3

首先进行更新,然后进行插入。像这样的东西。

update TargetTable 
set Col1 = SourceTable.Col1, 
    Col2 = SourceTable.Col2 
from SourceTable 
where TargetTable.ID = SourceTable.ID 

insert into TargetTable(Col1, Col2) 
select Col1, Col2 
from SourceTable 
where SourceTable.ID not in (select ID from TargetTable) 

更新:

如果在主键多列,您可以使用not exists代替。

update TargetTable 
set Col1 = SourceTable.Col1, 
    Col2 = SourceTable.Col2 
from SourceTable 
where TargetTable.ID1 = SourceTable.ID1 and 
     TargetTable.ID2 = SourceTable.ID2 

insert into TargetTable(Col1, Col2) 
select Col1, Col2 
from SourceTable 
where not exists (select * 
        from TargetTable 
        where TargetTable.ID1 = SourceTable.ID1 and 
        TargetTable.ID2 = SourceTable.ID2) 
+2

并将整个事情包装在一个事务中,以获得合并语句的相同事务完整性。 –

+0

@mikaeleriksson有一个问题,我的PK是双PK。我有ID1和ID2,所以有没有办法说SourceTable.ID和SourceTable.ID2不在(SELECT ID,ID2 FROM TargetTable)? – steventnorris

+0

解决了,只是向插入语句的内部选择添加了一个WHERE ID2 = SourceTable.ID2。谢谢! – steventnorris