我有一个表和一个数组,我想合并它们。
结构(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< 0然后插入。当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才会受到影响。
有人知道如何解决这个问题吗?
答案 0 :(得分: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;
答案 1 :(得分:0)
when not matched by source then delete;
^^^^^^^^^^^^^
如果您只想删除匹配项,请删除not
。