2011-09-01 77 views
1

說我有這兩個表:如何合併沒有主鍵的兩個表(或者如何讓合併的剩餘部分被刪除)?

 
    Table A        Table B 
_______________________   _______________________ 
Id | Description     Id | Description 
-----------------------   ----------------------- 
1 | Some Val      1 | Some Val      
2 | More Data      2 | More Data 
2 | Even More      2 | Less Is More 
2 | More again      3 | This Changed 
3 | Other Values     4 | these are random    
3 | But Not this     ------------------------ 
4 | these are random    
----------------------- 

我怎樣才能做一個合併,以表B的變化表A和得到這個:

 
    Table A      
_______________________    
Id | Description     
-----------------------    
1 | Some Val      
2 | More Data      
2 | Less Is More 
3 | This Changed 
4 | these are random    
----------------------- 

當我嘗試這樣的事:

merge TableA as target 
using (select Id, Description 
     from TableB) 
     as source (Id, Description) 
on (target.Id = source.Id)    
when MATCHED then 
    update set Id = source.Id, Description = source.Description 
when NOT MATCHED then 
    insert (Id, Description) 
    values (source.Id, source.Description); 

我得到這個錯誤:

The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

這是因爲Id不是唯一的。我可以添加說明,但不會更新。這意味着變更將孤兒行。

我真正需要的是一種說法:留下匹配的東西,插入丟失的東西並刪除剩下的東西。

我該怎麼做刪除部分?

注意:我意識到表A實際上只取表B的所有值。但我仍想合併,因爲在實踐中,這些表之間很少會發生變化。完整的截斷和重新插入是矯枉過正的。

回答

0

應該搜索了更長一點。需要的NOT MATCH ON SOURCE選項:

merge TableA as target 
using (select Id, Description 
     from TableB) 
     as source (Id, Description) 
on (target.Id = source.Id)    
when NOT MATCHED BY SOURCE then DELETE  
when NOT MATCHED then 
    insert (Id, Description) 
    values (source.Id, source.Description); 
0
merge TableA as target 
using (select * from TableB) as source 
on (target.id = source.id AND target.description = source.description)    
--when MATCHED then 
    --update set id = source.id, description = source.description 
when NOT MATCHED then 
    insert (id, description) 
    values (source.id, source.description) 
when NOT MATCHED BY source then DELETE;