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

标签 sql merge sql-server-2012

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

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

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

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

最佳答案

真的没有那么难......

你需要:

  • 提供数据的源表(或查询)
  • 一个目标表将其合并为
  • 检查这两个表的条​​件
  • 如果找到匹配项(在该条件下)该怎么做的语句
  • 如果没有找到匹配项(在该条件下)怎么办的语句

  • 所以基本上,它是这样的:
    -- 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);
    

    关于sql - 在 SQL Server 2012 中使用 MERGE 插入/更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771416/

    相关文章:

    java - Android Studio 访问 SQLite 数据库 Java

    mysql - SQL 查询获取 SUM 生成的新列的前 10 名

    mysql - 从mysql中的另一个表加入一行

    sql - 合并雪花 - 不匹配、更新和插入

    SQL Server - 忽略始终为真的条件

    sql - 从 xml 文件向 SQL Server 数据库添加行

    ruby-on-rails - 指定要与 git merge 的文件夹

    git - 仅在本地分支或本地和远程分支上为新功能创建分支?

    sql-server - SSIS 包在 Visual Studio 中运行良好,但在部署的机器上手动运行时失败

    reporting-services - 如何将 null 移动到 SSRS 中的复选框