如何使用MERGE语句更新多个条件

时间:2018-03-26 16:52:11

标签: sql sql-server sql-server-2016

我必须比较源数据和目标数据并相应地合并它们。但我有多个条件。 下面是我的第一组源数据

Source-Table1
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
2        2018-02-01     2199-12-31  Software Engineer


Target-Table2
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
2        2018-02-01     2199-12-31  Software Engineer


Create table Table1(
  Id int,
  StartDate datetime,
  EndDate   Datetime,
  Designation nvarchar(100)
  )

  Create table Table2(
  Id int,
  StartDate datetime,
  EndDate   Datetime,
  Designation nvarchar(100)
  )
--insert values
  insert into Table1 values(1,'2018-01-01','2199-12-31','Associate Engineer')
  insert into Table1 values(2,'2018-02-01','2199-12-31','Software Engineer')

  --Use Merge to Update/Insert values
MERGE Table2 t
  USING Table1 s
  on t.id=s.id
  WHEN MATCHED THEN 
  update SET
  t.id=s.id,
  t.StartDate=s.StartDate,
  t.EndDate=s.EndDate,
  t.Designation=s.Designation

  WHEN NOT MATCHED BY TARGET THEN
  INSERT(
  ID,
  StartDate,
  ENDDate,
  Designation
  )
  VALUES
  (s.ID,
  s.StartDate,
  s.EndDate,
  s.Designation)
  ;

现在,如果我必须更新多个条件,则此代码不起作用。 例如,如果我的源数据具有低于值,则每个ID不能具有重叠值。 当每个ID都有新记录时,我必须检查StartDate,如果开始日期是<然后,将我的旧endDate更新为上个月的最后一天 如果ID和StartDate匹配,则插入新记录,然后更新所有记录。如果ID和StartDate不是mach,则插入。

Source-Table1
ID       StartDate      EndDate     Designation
1        2018-01-01     2199-12-31  Associate Engineer
1        2018-02-01     2199-12-31  Software Engineer
2        2018-02-01     2199-12-31  Software Engineer
2        2018-03-01     2199-12-31  Senior Software Engineer

现在我希望我的目标表有

ID       StartDate      EndDate     Designation
1        2018-01-01     2018-01-31  Associate Engineer
1        2018-02-01     2199-12-31  Software Engineer
2        2018-02-01     2018-02-28  Software Engineer
2        2018-03-01     2199-12-31  Senior Software Engineer

我无法使用MERGE语句。你们中的任何人都可以帮助我获得这个结果吗?

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,那么您希望将源表与目标表合并。但是,如果用户的角色已更改,例如,副工程师与软件工程师,则您希望将原始记录的EndDate更新到新记录开始日期之前的月份的最后一天。 如果我的理解是正确的,那么您应该能够实现以下目标:

;MERGE  [Table2] [T]
USING   (
            SELECT       [T1].[Id]
                        ,[T1].[StartDate]
                        ,CAST(LEAD(EOMONTH(DATEADD(DAY, -1, [T1].[StartDate])), 1, [T1].[EndDate]) OVER (PARTITION BY [T1].[Id] ORDER BY [T1].[StartDate]) AS DATETIME) AS [EndDate]
                        ,[T1].[Designation]
            FROM        [dbo].[Table1] [T1]
        ) [S]
ON ([T].[Id] = [S].[Id] AND [T].[StartDate] = [S].[StartDate])
WHEN MATCHED THEN 
    UPDATE 
            SET [T].[EndDate] = [S].[EndDate],
                [T].[Designation] = [S].[Designation]
WHEN NOT MATCHED BY TARGET THEN
    INSERT
    (
      [Id],
      [StartDate],
      [EndDate],
      [Designation]
    )
    VALUES
    (
        [S].ID,
        [S].StartDate,
        [S].EndDate,
        [S].Designation
    );