What is USING in SQL Server 2008 MERGE syntax?

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

    A merge has a table source and a target table. This introduces the source table (which need not be an actual physical table, just a result set).

    The grammar is indicated in your question. To merge from another table or view use

    MERGE 
       Users
    USING SomeOtherTableName AS foo /*Alias is optional*/
    ON /* ... */
    

    Or you can use for example

    MERGE 
       Users
    USING master..spt_values
    UNPIVOT (X FOR Y IN ([high],[low])) AS foo 
    ON  
       Users.Username = foo.Y 
    WHEN MATCHED THEN
        UPDATE SET FirstName = foo.Y
    WHEN NOT MATCHED THEN
        INSERT (UserGUID, Username, FirstName, LastName, AuthenticationMethod)
        VALUES (foo.Y, foo.Y, foo.Y, foo.Y, foo.Y);
    

    For your bonus question you can use the VALUES clause here as part of the derived_table option.

    MERGE Users
    USING (VALUES ('{77410DC5-7A3E-4F1A-82C6-8EFB3068DE66}',
          'iboyd',
          'Ian',
          'Boyd',
          'Windows')) 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); 
    

提交回复
热议问题