我正在尝试创建merge语句 Insert, Update, Delete
在一个sp中,如下所示。
但我的要求是,在插入语句时,我需要添加多个具有不同值的insert,并在其中遇到问题。是否删除报表工作或我需要更改它?
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
1条答案
按热度按时间wqsoz72f1#
在“源”字段中,您可以使用查询,如果我是您,我会将目标与表示合并最终结果的查询合并:
另外,请注意,在比较匹配结果时,需要考虑空值: