【问题标题】:insert into table2 select from table1 if the whole row not exists in table2如果 table2 中不存在整行,则插入 table2 从 table1 中选择
【发布时间】:2019-02-25 07:50:56
【问题描述】:

我的问题是: 我有 2 个 sql server,我正在使用链接服务器从 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 行生效)。有什么建议吗?
我想让您知道,如果 server1 中的新记录或已编辑的记录在 server2 中不存在,我想更新 server2 表。
无论如何,谢谢你们。
日期:

查看上图,当 server1 中有 9 条记录而 server2 中的表为空时,查询有效并且所有 9 条记录都已插入到 server2 中,之后,我在 server1 中添加了一条新记录,即第 10 条记录,我执行了上面的查询,我得到了(0 行影响)。为什么没有插入新记录?

【问题讨论】:

  • 共享表结构和可能的样本数据

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


【解决方案1】:

在 not exist 语句中,您需要一个 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 )  

【讨论】:

    猜你喜欢
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多