首页 > 解决方案 > 如果不存在则插入,否则更新然后在旧记录上设置标志

问题描述

有人可以建议允许更新目录的最佳方法或存储过程。

假设我们每 2 个月收到一份新的分庭大律师名单。我们要

  1. 在不存在的地方插入新记录 - 基于名字、姓氏
  2. 如果它们存在,则更新某些可能为空白的字段,例如电话号码
  3. 将任何不在列表中的内容设置为 Live = 'N'

通常在 excel 或电子邮件中获取列表,因此必须清理数据。

select top 0 * into #temp from *table* 

Insert new data #temp

If not exists (select * from *table* where forename = 'X' and surname = 'Y' and ChambersID = 12) Insert into *table* (Title, forename, surname, yearofcall, ChambersID) values ('Mr','X', 'Y', 2018, 35) else update *table* set yearofcall = 2018 where forename = 'x' and surname = 'Y' and ChambersID = 12

This seems to work. Then i do another query. 

If not exists (select * from #temp where ChambersID = 12) update *table* set live = 'N' where ChambersID = 35

但冗长,因为必须在 excel 中构建半查询......更喜欢存储过程,我可以在其中传递名字,姓氏和 Chambersid

标签: sqlsql-server

解决方案


Merge请在 SQL 中尝试。它适合您的要求。这是一个片段

MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
    THEN update_statement
WHEN NOT MATCHED
    THEN insert_statement
WHEN NOT MATCHED BY SOURCE
    THEN DELETE;              --Instead of delete, set Live='N' in your case

推荐阅读