【问题标题】:Merge table with array将表与数组合并
【发布时间】:2013-02-08 10:38:19
【问题描述】:

我有一个表格和一个数组,我喜欢合并它们。

结构(t=目标,s=源):

ID          gID
----------- -----------
13          1
14          1
15          1
16          1
17          2
18          2
19          2

当 t.ID=s.ID 和 t.gID=s.gID 时,什么都不会发生。当 s.ID

我无法在合并查询中构建它:

merge tableT as t
using @array as s
on (t.ID = s.ID) and (t.gID=s.gID)
when not matched and s.ID < 0 then
insert into
when not matched by source then delete;

当每行@array 中的 gID=1 时,查询将删除所有 gID=2。 但只有 gID=1 应该受到影响。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: sql sql-server sql-merge


    【解决方案1】:

    您似乎应该将目标限制为与源中具有相同 gID 的行,如下所示:

    with tgt as (
      select *
      from tableT
      where gID in (select gID from @array)
    )
    merge tgt as t
    using @array as s
    on (t.ID = s.ID) and (t.gID=s.gID)
    when not matched and s.ID < 0 then
    insert into
    when not matched by source then delete;
    

    【讨论】:

      【解决方案2】:
      when not matched by source then delete;
          ^^^^^^^^^^^^^
      

      如果您只想删除匹配项,请删除 not

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        • 2021-06-20
        • 2014-07-24
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多