【问题标题】:How to use MERGE instead of INSERT INTO and UPDATE in SQL Server如何在 SQL Server 中使用 MERGE 而不是 INSERT INTO 和 UPDATE
【发布时间】:2014-10-20 00:42:55
【问题描述】:

我有一个包含以下内容的存储过程。

这用于检查某个ID是否存在。如果否,则将新记录插入表中,如果是,则更新现有记录。

该过程按预期工作,但我想知道是否可以使用 MERGE 来稍微改进代码。我如何使用 MERGE 来做到这一点,与我所拥有的相比有什么优点/缺点吗?

BEGIN
    IF NOT EXISTS
    (
        SELECT      * 
        FROM        MOC_Comments 
        WHERE       commentID = @commentID
    )
        BEGIN

            INSERT INTO MOC_Comments
            (
                    parentID, 
                    comment
            )
            SELECT  @parentID,
                    @comment
        END
    ELSE
        BEGIN

            UPDATE  MOC_Comments
            SET     parentID = @parentID,
                    comment = @comment
        END 
END

【问题讨论】:

标签: sql sql-server stored-procedures insert merge


【解决方案1】:

这是执行您正在寻找的基本合并语句:

我更新了合并的“更新”部分,以展示如何在不传递“set”方法中的每个参数的情况下更新记录。合并首先检查源(输入参数),如果为空,它将使用记录中的现有值。这允许您编写一个带有所有可为空参数的 set 方法,一个用于表或结构中的每一列(唯一约束或主键除外),并且只传入您想要更新相应记录列的参数。

merge into [dbo].[moc_comments] as target
using (values(@parentid
  , @comment
  , @commentid)) as source ([parentid], [comment], [commentid])
on target.[commentid] = source.[commentid]
when matched then
  update set target.[parentid] = coalesce(source.[parentid], target.[parentid])
         , target.[comment] = coalesce(source.[comment], target.[comment])
when not matched by target then
  insert ([parentid]
      , [comment]
      , [commentid])
  values ([parentid]
      , [comment]
      , [commentid]); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2017-12-19
    • 2014-09-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多