我正在使用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
答案 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;