mar*_*ark 4 sql merge sql-server-2008
我有两张桌子 - 来源和目的地.我想使用MERGE查询(SQL Server 2008)将源合并到目标.
我的设置如下:
这个设置应该很好地适用于MERGE语句语义,但我无法实现它.
我的不良尝试记录在这个SQL小提琴中
我究竟做错了什么?
编辑
BTW,而不是基于MERGE的解决方案就在这里.
小智 5
create table #Destination
(
    id          int,
    [Checksum]  int,
    [Timestamp] datetime
)
create table #Source
(
    id         int,
    [Checksum] int
)
insert #Destination
values (1, 1, '1/1/2001'),
       (2, 2, '2/2/2002'),
       (3, 3, getdate()),
       (4, 4, '4/4/2044')
insert #Source
values (1, 11),
       (2, NULL),
       (4, 44);
merge #destination as D
using #Source as S
on (D.id = S.id)
when not matched by Target then
    Insert (id, [Checksum], [Timestamp])
    Values (s.id, s.[Checksum], Getdate())
when matched and S.[Checksum] is not null then
    Update
    set D.[Checksum]=S.[Checksum],
        D.[Timestamp]=Getdate()
when not matched by Source then
    Delete
    Output $action, inserted.*,deleted.*;
select *
from #Destination
| 归档时间: | 
 | 
| 查看次数: | 4708 次 | 
| 最近记录: |