2011-03-29 79 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 
保持