使用t-sql MERGE复制或创建数据

时间:2019-05-01 20:40:45

标签: sql sql-server tsql

作为起点,我拥有tblMyTable之类的数据:

Id   Date
37   01/01/2019

或者我可能有:

Id   Date
37   01/01/2019
38   01/01/2018
39   01/01/2018

如果ID 38和39存在,我想将日期从Id = 37复制到ID 38和39。如果不存在ID 38和39,我想插入一个ID为38和Id = 39且日期从Id = 37开始的记录。

所以,在一天结束时,我想要拥有:

Id   Date
37   01/01/2019
38   01/01/2019
39   01/01/2019

tblMyTable开头是否包含38和39。

在理论上看来,我应该可以使用MERGE做到这一点,但我不知道USING子句如何工作。我是否只需要将其分解为两个语句?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用MERGE

with cte AS (
  select a.id, b.date from (
    select 38 id 
    union all
    select 39
  ) a cross join (
    select date from tblMyTable where Id = 37
  ) b
)

merge into tblMyTable t
using cte c on (t.id = c.id)
when not matched by target then
insert (id, date) values (c.id, c.date)
when matched then
update set date = c.date;

请参见demo

相关问题