1

我想在以下基础上使用 SQL Server 合并两个表:

IF the primary key (Operation) matches THEN
    If Source Date Matches Target Date
        Do nothing
    Else
        SET Target Revised_Date to Source Date
Else
    Insert Target Row from Source Row

我在下面构建了一个 SQL 合并,它执行第一阶段,但看不到如何执行第二阶段。

MERGE 
    Completed_Operations AS target
USING 
    @Completed_Operation_Table AS source ON (target.Operation = source.Operation)
WHEN MATCHED THEN 
    UPDATE 
    SET target.Revised_Completion_Date  = source.Completion_Date,
            target.Revised_Pln_Hrs          = source.Pln_Hrs,
            target.Revised_Pln_Hrs_Capped   = source.Pln_Hrs_Capped,
            target.Revised_Act_Hrs          = source.Act_Hrs
WHEN NOT MATCHED THEN   
    INSERT (Operation, Orig_Completion_Date, Orig_Pln_Hrs, Orig_Act_Hrs, Revised_Completion_Date, Revised_Pln_Hrs, Revised_Act_Hrs)
    VALUES (source.Operation, source.Completion_Date, source.Pln_Hrs, source.Act_Hrs, NULL, NULL, NULL);
4

1 回答 1

3

在 WHEN 子句中可以添加附加条件

MERGE
Completed_Operations AS target
USING 
@Completed_Operation_Table AS source ON (target.Operation = source.Operation)
WHEN MATCHED AND (source.Date <> target.Date) THEN
  UPDATE 
    SET target.Revised_Completion_Date  = source.Completion_Date,
        target.Revised_Pln_Hrs          = source.Pln_Hrs,
        target.Revised_Pln_Hrs_Capped   = source.Pln_Hrs_Capped,
        target.Revised_Act_Hrs          = source.Act_Hrs
WHEN NOT MATCHED THEN
  INSERT (Operation, Orig_Completion_Date, Orig_Pln_Hrs, Orig_Act_Hrs, Revised_Completion_Date, Revised_Pln_Hrs, Revised_Act_Hrs)
  VALUES (source.Operation, source.Completion_Date, source.Pln_Hrs, source.Act_Hrs, NULL, NULL, NULL);
于 2012-11-02T21:36:51.430 回答