sql - 如果不存在,则将 Table1 中的数据插入到 Table2 中,否则更新 table2 中的数据以匹配 Table1。在任何一种情况下,从 Table1 中删除
问题描述
我在 SQL Server 中有两个表(T1 和 T2),需要实现以下目标。
假设 T1 的列是 Item_ID,Units,T2 的列是 Item_ID,Units
对于 T1 中的每条记录,其中units > 5,如果该记录在 T2 中不存在,则将其插入到 T2 并从 T1 中删除
对于 T1 中units > 5 的每条记录,如果该记录确实存在于T2 中,则在T2 中更新它并从T1 中删除它
我尝试使用合并,但它对我不起作用,可能我无法以正确的方式完成。
我很感激任何帮助。
解决方案
首先,您需要在Table2上进行更新和插入;
merge table2 as target
using table1 as source
on target.ID = source.ID
when not matched by target and source.Units>5
then
insert (ID,Units) values (source.ID,source.Units)
when matched and source.Units>5
then
Update set Units = source.Units
OUTPUT $action,
inserted.ID AS InsertedID,
inserted.Units AS InsertedUnits;
然后你需要交换源表和目标表并删除指定的行;
merge table1 as target
using table2 as source
on target.ID = source.ID
when matched and source.Units>5
then
delete
OUTPUT $action,
deleted.ID AS DeletedID,
deleted.Units AS DeletedUnits;
推荐阅读
- data-structures - 改变蛇形工作流程以预测和适应不同的数据结构
- c# - dotnet core 3.0 WebApi、applicationPart和授权
- apache-nifi - nifi Json数据使用routeonattribute过滤属性或属性值
- javascript - 使用 setState() 时出现“没有重载匹配此调用”TypeScript 错误
- python - 如何将 dict 中的值组合到新的键/值对,用空字符串替换 None?
- c# - 具有外键列的列表视图源 (WPF MVVM)
- c++ - 如何生成比用户使用 rand() 函数输入的数字大 5-10% 的数字?
- r - R 无法将行名称分配给 get() 的矩阵输出
- javascript - 使用 JS fecth 获取特定数据
- c# - 启动时获取ExecutionContext.InvocationId(Azure函数V2)