gpt4 book ai didi

sql - 批量更新插入 SQL Server 2005

转载 作者:行者123 更新时间:2023-12-02 05:42:13 27 4
gpt4 key购买 nike

有没有办法在 SQL Server 2005 中进行批量更新插入?类似于 2008 年的 MERGE 的东西将是完美的。我有一个表用作临时工作区,需要在 session 完成时与主表协调。在 2008 年,merge 会为此做得很好,但我看到的唯一 2005 年方法是针对单个更新插入,而不是批量更新插入。想法?

最佳答案

先更新再插入。像这样。

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)

关于sql - 批量更新插入 SQL Server 2005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802089/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com