Question

I got a table and a array and I like to merge them.

Structure (t=target, s=source):

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

When t.ID=s.ID and t.gID=s.gID then nothing should happen. When s.ID < 0 then insert. When s.ID not exists then delete.

I'm not able to build this in a merge query:

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;

When the gID in the @array on every row=1, then the query deletes all with gID=2. But only the gID=1 should affected.

Someone know how to solve this?

Était-ce utile?

La solution

It seems like you should limit the target to just the rows with the same gID as in the source, something like this:

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;

Autres conseils

when not matched by source then delete;
    ^^^^^^^^^^^^^

If you'd like to delete only matches, remove the not.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top