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

时间:2015-03-02 18:23:19

标签: sql sql-server-2008 tsql

我搜索了这个主题的某些类型的帮助/答案,但我找不到多少。我问,因为我更喜欢MERGE;如果不可能,那么我将回到常规的更新/插入。

我有两个表:[Course][CourseHistory]。两者都有三列:EmpIdCourseIdCourseName。以下MERGE语句在必要时可以正常运行UPDATEsINSERTs[Course]

我需要包含的是在[CourseHistory]时加入UPDATE。基本上,我将备份即将修改的记录。

我尝试包含 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);

1 个答案:

答案 0 :(得分:2)

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

我会在$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'