在匹配语句时使用 MERGE 在其他 table 中更新和插入?

UPDATE and INSERT in other table with MERGE when matched statement?

我在这个主题上搜索了某种类型的 help/answers,但没有找到太多。我问是因为我更喜欢 MERGE;如果不可能,那么我会回到常规 Updates/Inserts.

我有两个表:[Course][CourseHistory]。两者都有三列:EmpIdCourseIdCourseName。以下 MERGE 语句在必要时从 UPDATEsINSERTs[Course] 的意义上正确工作。

我需要包括的是在有 UPDATE 时插入 [CourseHistory]。本质上,我将备份即将被修改的记录。

我尝试包含 INSERT 语句,但出现语法错误。

我的 tsql 语句如下所示:

merge dbo.Courses as pre              
using (select @EmpId as EmpId, @CourseId as CourseId) as S              
    on  pre.EmpId = S.EmpId and pre.CourseId = s.CourseId
  when matched then
   /* 
     INSERT INTO [CourseHistory] (EmpId, CourseId, CourseName)
     SELECT EmpId, CourseId, CourseName 
     where EmpId = @EmpId and @CourseId = CourseId
   */
    update set
        CourseName = @CourseName
  when not matched then              
    INSERT (CourseId, EmpId, CourseName)
    VALUES (@CourseId, @EmpId, @CourseName);

注意:我已经根据 rbhatup 的评论更新了我的答案。

我会在 $action 虚拟列中使用 OUTPUT ... INTO ... 子句,因此:

-- It create a temp. table with the same columns and data type like source table
SELECT TOP(0) *, CONVERT(NVARCHAR(10), N'') AS MergeAction 
INTO #AffectedRows 
FROM dbo.Courses;
-- If source table have one column with IDENTOTY property then this SELECT INTO will add also the IDENTITY property to the same column

MERGE... your statement ...
OUTPUT deleted.*, $action into  #AffectedRows; -- deleted = old values, inserted = new values

INSERT INTO [CourseHistory] -- You could add a new column to CourseHistory named [Action] (will store values from MergeAction)
SELECT * FROM #AffectedRows r
WHERE r.MergeAction = 'UPDATE'