在SQL Server 2012中使用MERGE插入/更新数据

New*_*bie 4 sql merge sql-server-2012

我正在使用SQL Server 2012并且有两个具有相同结构的表.如果表2中尚不存在新记录,我想从表1到表2插入新记录.

如果它们已经存在,我想更新表2中的所有现有记录.

我的表中有大约30列,我想更新所有列.

有人可以帮忙吗?我查看了通过互联网发布的各种链接,但我不明白我的陈述应该是什么样子.

mar*_*c_s 16

真的不是那么难......

你需要:

  • 用于提供数据的源表(或查询)
  • 要将其合并到的目标表
  • 检查这两个表的条​​件
  • 声明如果找到匹配(在该条件下)该怎么做
  • 如果找不到匹配(在该条件下),该怎么做

所以基本上,它是这样的:

-- this is your TARGET table - this is where the data goes into    
MERGE dbo.SomeTable AS target       
-- this is your SOURCE table where the data comes from 
USING dbo.AnotherTable AS source    
-- this is the CONDITION they have to "meet" on
ON (target.SomeColumn = source.AnotherColumn)  

-- if there's a match, so if that row already exists in the target table,
-- then just UPDATE whatever columns in the existing row you want to update
WHEN MATCHED THEN                           
    UPDATE SET Name = source.Name,
               OtherCol = source.SomeCol

-- if there's NO match, that is the row in the SOURCE does *NOT* exist in the TARGET yet,
-- then typically INSERT the new row with whichever columns you're interested in
WHEN NOT MATCHED THEN  
    INSERT (Col1, Col2, ...., ColN)  
    VALUES (source.Val1, source.Val2, ...., source.ValN);
Run Code Online (Sandbox Code Playgroud)