2012-05-29 42 views
3

我在將信息從一個表插入到其他表時存在一個小問題。刪除插入後存在的重複條目

例如:從table A(可包含〜10個KK條目)table B,表是相同的,除了table A具有DateTimeStamp其用於採取某些數據(邊界)。

所以我需要將數據從A移動到B(無DateTimeStamp)和來自枯草

實施例刪除重複:

表A

DateTimeStamp | Key | value 
2012-02-03 | 2 | 123 
2012-02-03 | 3 | 985 
2012-02-03 | 5 | 1584 

表B

Key | value 
    8 | 45 
    3 | 785 
    9 | 7457 

所以我需要刪除Key = 3Table B行並插入Table A其他所有內容。

結果將是:

Key | value 
    8 | 45 
    3 | 985 
    9 | 7457 
    2 | 123 
    5 | 1584 

有優雅的方式來做到這一點?觸發器速度太慢,我正在尋找不需要臨時表的解決方案。

SQL Server或SSIS解決方案\建議,歡迎

+0

哪個版本** ** SQL Server的oledbdestination? 2008年將有'MERGE'命令,這將是完美的這種情況下 –

+0

2008年,感謝您的建議,我會嘗試與MERGE –

+0

行 - 請參閱我的迴應MERGE語句的示例 –

回答

3

如果您使用的SQL Server 2008 更新,你可以用一個單一的MERGE語句做到這一點很容易 - 這樣的事情:

MERGE INTO dbo.B    -- target table 
USING A ON b.Key = a.Key  -- source table and "link" information 
WHEN MATCHED 
    THEN UPDATE SET B.Value = A.Value -- if "Key" already present in B - update "Value" 
WHEN NOT MATCHED      -- if "Key" not present in B - insert new row 
    THEN INSERT(TblKey, TblValue) VALUES(A.TblKey, A.TblValue) 
WHEN NOT MATCHED BY SOURCE 
    DELETE        -- if present in B, but not in A -> remove 
; 
+0

這將做的事情:)它只一次,當使用1kk或更多的條目時。 –

1

兩個步驟:

-- first delete 
delete tableB 
from tableB b 
inner join tableA a on b.Key = a.Key 

-- then insert 
insert into tableB 
select a.Key, a.Value from tableA a where a.Key not in (select b.Key from tableB b) 
0

試試這個:

delete FROM tableB Where tableB.Key IN 
    (select Key 
    from tableA 
    INTERSECT 
    select Key 
    from tableB) 

然後插入:

從表B中刪除重複進入表B:

insert INTO tableB (Key, Value) 
select Key, Value From tableA 
0

即使這裏介紹的所有解決方案似乎工作,我真的會建立一個包處理與10kk行的表。

您可以使用帶查詢aF的oledbsource。建議:

select a.Key, a.Value 
from tableA a 
where a.Key not in (select b.Key from tableB b) 

,並直接發送到指向表B