-1

所以我在这个网站上做了一些挖掘,除了一个 case 语句来更新 SQL Merge 中的两列之外没有任何骰子。我还有一个问题。你可以在匹配的场景中做两个选项吗?我想在匹配时进行更新和插入。这可能吗?你能发布一个例子吗?我的最终目标是更新旧记录并在目标表中插入新记录。

 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); 
4

1 回答 1

0

我在回滚时将MERGE语句包装在事务中并检查输出。语句也可以是CTE的最后一部分。您可以在具有不同子句的 a 中包含多个,和语句。MERGEUPDATEINSERTDELETEMERGEWHERE

注意:在合并语句中,连接中的每个列不能有多行。

代码:

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
于 2018-10-10T22:04:04.480 回答