首页 > 解决方案 > 如果不存在,则将 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 中删除它

我尝试使用合并,但它对我不起作用,可能我无法以正确的方式完成。

我很感激任何帮助。

标签: sqlsql-serverdatabase

解决方案


首先,您需要在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;

推荐阅读