Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如果不存在,则插入else更新,然后在旧记录上设置标志_Sql_Sql Server - Fatal编程技术网

Sql 如果不存在,则插入else更新,然后在旧记录上设置标志

Sql 如果不存在,则插入else更新,然后在旧记录上设置标志,sql,sql-server,Sql,Sql Server,有人能建议最好的方法或存储过程来更新目录吗 假设我们每两个月收到一份新的律师名单。我们需要 在不存在的地方插入新记录-基于名字、姓氏 如果存在,则更新某些可能为空的字段,例如电话号码 将任何不在列表中的设置为Live='N' 通常在excel或电子邮件中获取列表,因此必须清理数据 select top 0 * into #temp from *table* Insert new data #temp If not exists (select * from *table* where fo

有人能建议最好的方法或存储过程来更新目录吗

假设我们每两个月收到一份新的律师名单。我们需要

在不存在的地方插入新记录-基于名字、姓氏 如果存在,则更新某些可能为空的字段,例如电话号码 将任何不在列表中的设置为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的存储过程,请尝试在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

你看过MERGE吗?如果没有,你试过什么?嘿,不是作为评论。改为编辑您的问题。这是否回答了您的问题@我已经在我的例子中这样做了。这个方法最适合我。我将尝试创建一些变量,然后创建一个存储过程。