sql - 如果不存在则插入,否则更新然后在旧记录上设置标志
问题描述
有人可以建议允许更新目录的最佳方法或存储过程。
假设我们每 2 个月收到一份新的分庭大律师名单。我们要
- 在不存在的地方插入新记录 - 基于名字、姓氏
- 如果它们存在,则更新某些可能为空白的字段,例如电话号码
- 将任何不在列表中的内容设置为 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
解决方案
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
推荐阅读
- python - 将 send_keys 限制为特定数量的字符
- spotfire - 如何取消合并 Spotfire 交叉表中的行
- php - 如何将 postfix 配置为可以登录的 SMTP 服务器?
- android - 设置任务描述时android应用程序崩溃
- python - BeautifulSoup.get_text() 忽略换行符
- python-3.7 - 在 python 3.7.4 0 中使用附加模式创建的文件
- java - 声明一个继承自 Employee 类的 Manager 类 (Java)
- python - Pyspark Grouped Map Pandas UDF - 它是否保持组中行的顺序?
- java - 我得到了我在 networkstatsmanager.querydetailsforuid() 方法中提供的不同的 startTimestamp 和 endtimestamp。如何解决?
- spring - Hibernate 不添加 auto_increment