根据另一个表在表中添加或删除

时间:2011-03-29 18:13:33

标签: sql-server sql-server-2005

我有一张类似这样的表:

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

我想根据table2删除或添加记录到table1。 所以根据table2删除和添加table1后,这将是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

实现它所需的查询是什么

2 个答案:

答案 0 :(得分:0)

已编辑的回答

从table2添加到table1

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

从table1删除

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

更新table1(假设您也想更新已更改的记录)

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

答案 1 :(得分:0)

假设table2具有TIME列

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

如果table2没有TIME列,那么很难处理您的数据。什么是“1:2”?这是一些迄今未知的时间格式吗?什么应该“现在”以相同的格式产生?

如果“1:2”只代表一个常规的日期时间,那么时间将保留在条款上的table1 上(1)License&amp;表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