What is USING in SQL Server 2008 MERGE syntax?

后端 未结 3 1667
借酒劲吻你
借酒劲吻你 2020-12-14 08:12

Jacob asked the perfect question: give me the MERGE syntax.

Every answer out there immediately jumps to the most complicated case they can think of; obscuring the sy

3条回答
  •  既然无缘
    2020-12-14 08:42

    Source table can be anything, such as:

    MERGE 
       member_topic AS target
    USING 
       (SELECT @Variable1, @Variable2, @Variable3) AS source(Col1, Col2, Col3)
    ON 
       target.mt_member = source.Col1 
       AND source.Col1 = 0 
       AND source.Col2 = 110
    WHEN MATCHED THEN 
       UPDATE SET mt_notes = 'test'
    WHEN NOT MATCHED THEN 
       INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test');
    

    Obviously, in the nested source select you can do many more things. Select from a view, a function, a table variable, a CTE even.

    As for the bonus question, you answered your own question.

    Sometimes,for very large tables, I also use the ROWLOCK hint on the target table, to at least try not to lock the entire table in case of updates:

    MERGE 
       member_topic WITH (ROWLOCK) AS target
    

    Related to the bonus question not working, here's a working sample. I renamed some of the objects, of course.

    DECLARE @Variable1 AS INT;
    SET @Variable1 = 1234;
    
    MERGE dbo.Table1 WITH(ROWLOCK) target
    USING(SELECT @Variable1) source(Key)
    ON target.[Key] = source.[Key]
    WHEN MATCHED THEN
        UPDATE SET
        Col1 = @SomeVar1,
        Col2 = @SomeVar2
    WHEN NOT MATCHED THEN
    INSERT 
            ([Key]
            ,[Col1]
            ,[Col2])
        VALUES
            (@Variable1
            ,@SomeVar1
            ,@SomeVar2);
    

提交回复
热议问题