【问题标题】:Merge Statement in SQL Statement Add, Update, Delete in single SPSQL 语句中的合并语句在单个 SP 中添加、更新、删除
【发布时间】: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


    【解决方案1】:

    在源字段中,您可以使用查询,如果我是您,我会将目标与表示合并最终结果的查询合并:

    MERGE Table1 AS TARGET
    USING (select value, value from tableX join tableY ...) AS SOURCE 
    

    另外,请注意,在比较匹配结果时,您需要考虑空值:

    when matched and (source.val != target.val or source.val is null and target.val is not null or source.val is not null and target.val is null)
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多