【问题标题】:Is there a way to copy data from table A into Table B if it does not exist in Table B?如果表 B 中不存在数据,有没有办法将表 A 中的数据复制到表 B 中?
【发布时间】:2019-05-21 05:25:15
【问题描述】:

我在两个不同的服务器中有两个表,但服务器是链接的。我想比较一台服务器的表 A 和另一台服务器的表 B。如果表 B 有表 A 没有的记录,我想复制该记录并将其插入表 A。我尝试使用 Insert Into Select 语句,但无法执行。任何帮助,将不胜感激。谢谢你

我尝试使用 Insert Into Select 语句,但无法执行。

INSERT INTO PHYSICAL_INVENTORY  (ITEMKEY, ITEM_NUMBER, WHSE_BIN_KEY, 
CONTROL_NUMBER)
SELECT T.ItemKey, I.ItemID, T.WhseBinKey, T.CtrlNo
from [Server B].prod.dbo.counttran T
inner join [Server B].prod.dbo.timItem I on I.ItemKey = T.ItemKey
Where ITEMKEY <> T.ItemKey

【问题讨论】:

  • 看起来应该执行但不返回任何行(因为您加入itemkey = itemkey,但随后过滤到itemkey &lt;&gt; itemkey,不能两者兼而有之)。它是抛出错误还是不返回任何结果?查询肯定需要调整,但如果它没有执行,那么这也表明存在不同的问题。
  • How can I do an insert where not exists? 的另一个可能副本
  • SQL Server Insert if not exist 的其他可能副本
  • Aaron 它确实会引发一般性错误,例如在 itemkey 和其他变体之前无效的内容

标签: sql


【解决方案1】:

也许NOT EXISTS 就是您要搜索的内容。

INSERT INTO physical_inventory
            (itemkey,
             item_number,
             whse_bin_key, 
             control_number)
            SELECT b.itemkey,
                   b.itemid,
                   b.whsebinkey,
                   b.ctrlno
                   FROM [Server B].prod.dbo.counttran b
                   WHERE NOT EXISTS (SELECT *
                                            FROM physical_inventory a
                                            WHERE a.itemkey = b.itemkey
                                                  AND a.item_number = b.itemid
                                                  AND a.whse_bin_key = b.whsebinkey
                                                  AND a.control_number = b.ctrlno);

(如果表有主键并且比较它们就足够了,那么exists中的WHERE可能会被简化。)

【讨论】:

  • 很抱歉,迟到的回复被其他东西包裹起来了。我会尝试你的解决方案粘性位。
  • 稍作调整即可工作。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多