【发布时间】:2020-06-08 11:50:14
【问题描述】:
我正在尝试在一个 SP 中创建合并语句来执行 Insert, Update, Delete,如下所示。
但我的要求是在插入语句时,我需要添加多个具有不同值的插入,并在其中面临问题。 Delete Statement 会起作用还是我需要更改它?
Declare @Project_Id INT =12;
MERGE Table1 AS TARGET
USING Table2 AS SOURCE
ON (TARGET.Id = SOURCE.Id AND TARGET.Project_Id = SOURCE.Project_Id)
--When records are matched, update the records if there is any change
WHEN MATCHED AND TARGET.Name <> SOURCE.Name AND TARGET.Project_Id = @Project_Id
THEN UPDATE SET TARGET.Name = SOURCE.Name, Target.Project_Id= @Project_Id
--When no records are matched, insert the incoming records from source table to target table
WHEN NOT MATCHED BY TARGET
THEN
INSERT (project_id,Financials_Desc,created_date,createdby,Name,Id) Values
(@PROJECT_ID,'Gross Sales (or BGA) Total - Launch
Year',CURRENT_TIMESTAMP,@createdby,Source.Name,Source.Id )
INSERT (project_id,Financials_Desc,created_date,createdby,Name,Id) Values
(@PROJECT_ID,'Gross Sales (or BGA) Total -
Ongoing',CURRENT_TIMESTAMP,@createdby,Source.Name,Source.Id )
--When there is a row that exists in target and same record does not exist in source then delete
this record target
WHEN NOT MATCHED BY SOURCE
THEN DELETE
【问题讨论】:
标签: sql sql-server merge