What is USING in SQL Server 2008 MERGE syntax?

后端 未结 3 1675
借酒劲吻你
借酒劲吻你 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:59

    Following on from Martin Smith's answer, you can upsert several explicit value rows at once simply by repeating the brackets, separating with a comma, eg,

    MERGE Users WITH (HOLDLOCK)
    USING (VALUES ('{77410DC5-7A3E-4F1A-82C6-8EFB3068DE66}',
          'iboyd',
          'Ian',
          'Boyd',
          'Windows'),
          ('{00000DC5-7A3E-4F1A-82C6-8EF452D2DE66}',
          'jsmith',
          'John',
          'Smith',
          'ActiveDirectory')) AS foo(UserGUID, Username, FirstName, LastName, AuthenticationMethod)
    ON Users.UserName = foo.UserName
    WHEN MATCHED THEN
      UPDATE SET Firstname = foo.FirstName,
                 Lastname = foo.LastName
    WHEN NOT MATCHED THEN
      INSERT (UserGUID,
              Username,
              FirstName,
              LastName,
              AuthenticationMethod)
      VALUES (UserGUID,
              Username,
              FirstName,
              LastName,
              AuthenticationMethod); 
    

    Tested this on SQL Server 2012. (Would have added this as a comment but too many characters.)

    I added a HOLDLOCK having seen this, because if you're using MERGE for UPSERT surely the point is locking, the syntax is certainly no clearer. See also Marcel's comment on ROWLOCK for large tables.

    There was another post I found clearer than average, too.

提交回复
热议问题