2011-03-29 36 views
0

添加或從表中刪除我有一個表是這樣的一個:根據其它表

table1: 
Id License Major  time 
2 9   0012  1:2 
1 8   0014  1:2 
2 9   0017  2:5 
1 7   0016  2:7 
1 6   0019  2:8 

,我有其他的表是這樣的一個:

table2 
Id License  Major 
1  8   0014 
1  7   0016 
1  10   0019 

我想根據表2從table1中刪除或添加記錄。 所以刪除,並根據表2,從表1加入後,這將是table1的

table1 
Id License Major  time 
2 9   0012  1:2 
1 8   0014  1:2 
2 9   0017  2:5 
1 7   0016  2:7 
1 10   0019  Now 

什麼是實現它

+1

爲什麼要保留許可證9,但放棄許可證6? – 2011-03-29 18:20:28

+0

假設我有兩個用戶,他們的ID是1和2,用戶1正在編輯他/她的專業和許可證。並想要刪除License6。 – 2011-03-29 18:26:56

回答

0

EDITED答案

從表2添加到表1所需要的查詢

INSERT INTO table1 
    (Id, 
    License, 
    Major, 
    time) 
SELECT 
    Id, 
    License, 
    Major, 
    GetDate() 
FROM table2 t2 
LEFT JOIN table1 t1 on t1.ID = t2.ID and t1.License = t2.License 
WHERE t1.ID IS NULL 

從表格1刪除

DELETE 
FROM table2 t2 
WHERE NOT Exists (SELECT 
       License 
       FROM table1 t1 
       Where t1.ID = t2.ID AND t1.License = t2.License) 

更新表1(假設你想更新已變更記錄以及)

Update t1 
    SET License = t2.License, 
     Major = t2.Major, 
     time = GetDate() 
FROM table1 t1 
INNER JOIN table2 on t2.ID = t1.ID and t2.License = t1.License 
WHERE t1.Major <> t2.Major 
0

假設表2有足夠的時間列

begin tran 
; 
delete table1 where id in (select id from table2) 
; 
insert table1 (Id, License, Major, time) 
select Id, License, Major, time 
from table2 
; 
commit 

如果表2沒有一個TIME列,那麼很難處理你的數據。什麼是「1:2」?那是一些迄今爲止未知的時間格式嗎? 「現在」應該以相同的格式生成什麼?

如果「1:2」只是表示一個普通的日期時間,和時間從表1 上條件(1)許可證&主要在表2匹配現有許可證&主要在表1,然後

begin tran 
; 
delete a 
from table1 a 
left join table2 b 
    on a.id=b.id and a.license=b.license and a.major=b.major 
where b.id is null 
; 
insert table1 (Id, License, Major, time) 
select a.Id, a.License, a.Major, GetDate() 
from table2 a 
left join table1 b 
    on a.id=b.id and a.license=b.license and a.major=b.major 
where b.id is null 
; 
commit 
保持