sql - 从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
解决方案
您可以分两部分执行此操作:
- 首先检查那些添加到 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)
- 然后检查那些从 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)
推荐阅读
- java - MySQL 无法 ALTER TABLE 正在积极写入
- javascript - JavaScript 模块的反射/自省
- java - Java:将文件从一个目录复制/移动到另一个目录的安全方法
- c++ - 抛出的异常从未被捕获,但线程没有被杀死?
- angular - Angular2 - 在字符串中动态包含 routerLink
- c - PlatformIO 构建失败:未定义对 http_parser_init 的引用
- node.js - NodeJs TypeError:无法读取未定义的属性“键”
- activejdbc - 无法在 Gitlab CI 上通过测试
- jquery - Summernote 初始化后如何更改选项?
- javascript - onTouch 事件不起作用