首页 > 解决方案 > 从sql中的第二个表中的第一个表中删除的身份记录

问题描述

我有这样的表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

标签: sqlsql-server

解决方案


您可以分两部分执行此操作:

  1. 首先检查那些添加到 tableA 并将它们插入到 tableB 中的那些。
    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)
  1. 然后检查那些从 tableB 中删除的并更新 enddate
    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)

推荐阅读