gpt4 book ai didi

sql - 如何在 Sql Server 2008 中的一个 MERGE 查询中更新、插入、删除?

转载 作者:行者123 更新时间:2023-12-04 21:17:02 26 4
gpt4 key购买 nike

我有两个表 - 源和目标。我想使用 MERGE 查询 (SQL Server 2008) 将源合并到目标中。

我的设置如下:

  • 每个目标记录都有三个字段(在实际应用中,当然不止 3 个)——id、校验和和时间戳。
  • 每个源记录有两个字段 - id 和校验和。
  • 如果没有具有相同 id 的目标记录,则将源记录插入到目标中。
  • 如果源记录校验和不为空,则目标记录将从具有相同 ID 的源记录更新。可以保证,如果校验和不是 NULL,则它与相应的目标校验和不同。这是给定的。
  • 如果没有相同 id 的源记录,则目标记录将被删除。

  • 这种设置应该非常适合 MERGE 语句语义,但我无法实现它。

    我的糟糕尝试记录在此 SQL Fiddle

    我究竟做错了什么?

    编辑

    顺便说一句,不是基于 MERGE 的解决方案是 here .

    最佳答案

    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

    关于sql - 如何在 Sql Server 2008 中的一个 MERGE 查询中更新、插入、删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945472/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com