如果没有ID记录,SQL Server合并语句将返回零

时间:2019-05-16 11:24:57

标签: sql-server merge

我正在使用merge语句更新ModuleEnrollment表中完成的课程数量。这是可行的,但是,如果从雇员中删除课程,则它仍将保持其先前的值。有没有一种方法可以包含在合并语句中,以为EmployeeID表中未包含的任何CoursesComplete返回0。

 MERGE [dbo].[ModuleEnrollment] as ME
 USING  [dbo].[CoursesComplete]AS CC
 ON ME.[EmployeeID] = CC.[EmployeeID] AND ME.[ModuleID] = CC.[ModuleID]
 WHEN MATCHED THEN
      UPDATE SET ME.[CoursesComplete]=CC.[CoursesComplete]
 WHEN NOT MATCHED BY TARGET THEN
      INSERT([EmployeeID],[ModuleID],[CoursesComplete]) VALUES(CC. 
[EmployeeID],CC.[ModuleID],CC.[CoursesComplete]);

GO

1 个答案:

答案 0 :(得分:1)

您只需添加:

WHEN NOT MATCHED BY SOURCE THEN 
    UPDATE SET ME.[CoursesComplete]=0

整个查询:

;MERGE [dbo].[ModuleEnrollment] as ME
 USING  [dbo].[CoursesComplete]AS CC
 ON ME.[EmployeeID] = CC.[EmployeeID] AND ME.[ModuleID] = CC.[ModuleID]
 WHEN MATCHED THEN
      UPDATE SET ME.[CoursesComplete]=CC.[CoursesComplete]
 WHEN NOT MATCHED BY TARGET THEN
      INSERT([EmployeeID],[ModuleID],[CoursesComplete]) VALUES(CC. 
[EmployeeID],CC.[ModuleID],CC.[CoursesComplete])
WHEN NOT MATCHED BY SOURCE THEN 
        UPDATE SET ME.[CoursesComplete]=0;