如果整个行不存在于表2中,则插入表2中,从表1中选择

时间:2019-02-25 07:50:57

标签: sql sql-server sql-insert linked-server

我的问题是: 我有2个sql服务器,我正在使用链接服务器从server1更新server2上的表。
我正在使用此查询:

 insert into   [server2].[db2].[dbo].[pcodes] (parcode,pname,unit,typ) select parcode,pname,unit,typ from [server1].[db1].[dbo].[pcodes] where not exists (select parcode,pname,unit,typ from  [server2].[db2].[dbo].[pcodes])      

该代码仅在server2上的表为空时有效,因此当我第一次执行查询时,但是在此之后,当我在server1上添加新记录并执行查询时,我得到的是(0行生效)。有什么建议吗?
我想让您知道,如果server2中不存在新的或已编辑的记录,那么我想更新server2表。
谢谢大家。
UODATE:

enter image description here

检查上图,当记录为server1中的9条记录,而server2中的表为空时,查询工作正常,所有9条记录均已插入到server2中,之后,我在server1中添加了一条新记录第10条记录,我引用了上面的查询,得到了(影响0行)。为什么未插入新记录?

1 个答案:

答案 0 :(得分:2)

在不存在语句中,您需要具有where条件,查询缺少该条件,

         INSERT INTO   [server2].[db2].[dbo].[pcodes]  (parcode,pname,unit,typ) 
              SELECT parcode,pname,unit,typ 
              FROM [server1].[db1].[dbo].[pcodes] a 
              WHERE NOT EXISTS 
              (SELECT parcode,pname,unit,typ from  [server2].[db2].[dbo].[pcodes] b
              WHERE a.parcode=b.parcode and a.pname=b.pname and a.unit=b.unit and a.typ=b.typ )  
相关问题