如果表b中未找到记录,则表A上的SQL Server更新

时间:2016-04-28 08:32:52

标签: sql-server

有以下表格:

表名PLANS

字段名称

Key  EMP _ID
Key  PLAN_NUMBER
STATUS
FIELD1
FIELD2
FIELD3
FIELD4

表名PLANS_TEMP

Key  EMP_ID
Key  PLAN_NUMBER
STATUS
FIELD1
FIELD2
FIELD3
FIELD4

想要PLANS_TEMP表中的PLANS数据。

如果PLANS_TEMP

中不存在记录,则不想删除记录而是要设置status ='I'
  1. 如果Office_Plan_temp中不存在记录,则需要更新Office_Plan.Status ='我'
  2. 如下所示:

    Update P
    Set status = ‘I’
    Where emp_id and plan_number not exists in Plans_Temp table
    

    (我们必须匹配LOCATION_ID& PLAN_NUMBER)

    1. 如果在Plans_Temp表中找到记录但未在Plans表中找到,则要插入。

    2. 对于所有现有记录,想要检查field1,field2,field3和field4是否有任何更改,然后更新。

    3. 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这样的事可能会对你有所帮助:

MERGE PLANS as target
USING PLANS_TEMP as source
ON target.EMP_ID = source.EMP_ID AND target.PLAN_NUMBER = source.PLAN_NUMBER
--If record doesn’t exists in Office_Plan_temp Wants to update Office_Plan.Status = ‘I’
WHEN NOT MATCHED BY SOURCE THEN
    UPDATE SET [STATUS] = 'I'
--If Record found in Plans_Temp table but not in Plans table, wants to insert.
WHEN NOT MATCHED BY TARGET THEN
    INSERT (EMP_ID, PLAN_NUMBER, [STATUS], FIELD1, FIELD2, FIELD3, FIELD4)
    VALUES (source.EMP_ID, source.PLAN_NUMBER, source.[STATUS], source.FIELD1, source.FIELD2, source.FIELD3, source.FIELD4)
--For all the existing records, (! HERE UPDATE WITHOUT ANY CHECKING wants to check if there’s any change in) field1, field2, field3 and field4 then update.
WHEN MATCHED THEN 
    UPDATE SET  target.FIELD1 = source.FIELD1,
                target.FIELD2 = source.FIELD2,
                target.FIELD3 = source.FIELD2,
                target.FIELD4 = source.FIELD4;