Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL Server中使用合并而不是插入和更新_Sql_Sql Server_Stored Procedures_Insert_Merge - Fatal编程技术网

如何在SQL Server中使用合并而不是插入和更新

如何在SQL Server中使用合并而不是插入和更新,sql,sql-server,stored-procedures,insert,merge,Sql,Sql Server,Stored Procedures,Insert,Merge,我有一个包含以下内容的存储过程 这用于检查是否存在某个ID。如果否,则将新记录插入表中;如果是,则更新现有记录 该过程按预期工作,但我想知道是否可以使用MERGE来实现同样的效果,从而稍微改进代码。我如何使用MERGE实现这一点?与我现有的相比,有哪些优点/缺点 BEGIN IF NOT EXISTS ( SELECT * FROM MOC_Comments WHERE commentID =

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

这用于检查是否存在某个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

下面是基本的merge语句,用于执行您要查找的操作:

我更新了合并的“更新”部分,以显示如何更新记录,而无需在“set”方法中传入每个参数。合并首先检查源(输入参数),如果为null,它将使用记录中的现有值。这允许您使用所有可为null的参数编写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]); 

《如何合并》“最佳实践”可能重复,你可以在这里找到:你也可以找到这篇关于性能的有趣文章:谢谢,我来看看。