2013-02-08 46 views
1

我得到了一個表和一個數組,我喜歡合併它們。與數組合並表

結構(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; 

當GID在每一行= 1 @array,那麼查詢刪除所有與GID = 2。 但是隻有gID = 1纔會受到影響。

有人知道如何解決這個問題嗎?

回答

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; 
0
when not matched by source then delete; 
    ^^^^^^^^^^^^^ 

如果你想刪除只匹配,取出not