2

有没有办法在 SQL Server 2005 中批量更新插入?类似于 2008 年的 MERGE 将是完美的。我有一个表作为临时工作区工作,需要在会话完成时与主表进行协调。在 2008 年,merge 可以很好地解决这个问题,但我见过的唯一 2005 年方法是针对单个 upsert,而不是批量。想法?

4

1 回答 1

5

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

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)
于 2012-05-29T15:52:14.953 回答