在匹配方案中具有多个选项的T-SQL合并

时间:2018-10-10 21:16:13

标签: tsql merge azure-sql-database ssms-2017

因此,我在此站点上进行了一些挖掘,没有骰子,除了要更新SQL Merge中两列的case语句。我还有另一个问题。您可以在匹配的方案中做两个选择吗?我想在“匹配时”进行更新和插入。这可能吗?你能举个例子吗? 我的最终目标是更新旧记录并在目标表中插入新记录。

 Merge Table1 as targ
using Table2 as sour

on table1ID  = Table2ID 

When  MATCHED 

    Then  update col1 = sour.col2 

    Then insert (col1,col2,col3)
    values (sour.col1,sour.col2,sour.col3)

When Not Matched 

    Then insert (col1,col2,col3)
    values (sour.col1,sour.col2,sour.col3); 

1 个答案:

答案 0 :(得分:0)

我将MERGE语句包装在rollback上的事务中,并检查输出。 MERGE语句也可以是CTE的最后一部分。您可以在UPDATE中使用不同的INSERT子句使用多个DELETEMERGEWHERE语句。

  

注意:在merge语句中,联接中的每一列不能有多行。

代码:

SET XACT_ABORT ON  --When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
BEGIN TRANSACTION;

    MERGE Table1 AS T
    USING Table2 AS S
        ON --<< Update the join to the correct unique key for the table (can't have duplicate rows)
            T.[col1] = S.[col1]
        AND T.[col2] = S.[col2]
        AND T.[col3] = S.[col3]
    WHEN NOT MATCHED BY TARGET -- AND 1=2 --<< you can include a where clause here
        THEN INSERT
        (
           [col1], [col2], [col3]
        )
        VALUES
        (
           S.[col1], S.[col2], S.[col3]
        )
    WHEN MATCHED  -- AND 1=2 --<< you can include a where clause here
        THEN UPDATE SET
          T.[col1] = S.[col1]
        , T.[col2] = S.[col2]
        , T.[col3] = S.[col3]
    --WHEN NOT MATCHED BY SOURCE -- AND 1=2 --<< you can include a where clause here
        --THEN DELETE
    OUTPUT @@SERVERNAME AS [Server_Name], DB_NAME() AS [Database_Name], $action, inserted.*, deleted.*;

ROLLBACK TRANSACTION;
--COMMIT TRANSACTION;

GO