我有这样的表A:
Ordernumber PartId
--------------------------
10134 6
10134 7
表B:
OrderId OrderNumber PartId Startdate enddate
---------------------------
1 10134 6 4/5/2019 null
1 10134 8 4/5/2019 null
我想确定已插入表A的新零件ID,并将这些新零件ID插入表B。
我想确定在表A中删除的旧零件ID,并最终确定表B中的记录,并在相关表中执行其他操作。
所以最终结果应该是:
表B:
OrderId OrderNumber PartId Startdate enddate
---------------------------
1 10134 6 4/5/2019 null
1 10134 8 4/5/2019 7/25/2019
1 10134 7 7/25/2019 null
答案 0 :(得分:0)
您可以分为2部分:
insert into tableB (OrderId,OrderNumber,PartId,startDate)
select a.OrderId,a.OrderNumber,a.PartId,getdate() as startDate
from tableA as a
where not exists (select 1 from tableB as b where a.OrderId = b.OrderId and a.OrderNumber = b.OrderNumber and a.PartId = b.PartId)
update b
set b.enddate = getdate()
from tableB as b
where not exists (select 1 from tableA as a
where a.OrderId = b.OrderId and a.OrderNumber = b.OrderNumber and a.PartId = b.PartId)