简体   繁体   English

如果表B中不存在数据,是否可以将数据从表A复制到表B中?

[英]Is there a way to copy data from table A into Table B if it does not exist in Table B?

I have two table in two different servers, but the servers are linked. 我在两个不同的服务器中有两个表,但是服务器是链接的。 I would like to compare Table A from one server and Table B from the other. 我想比较一台服务器的表A和另一台服务器的表B。 If table B has a record that Table A does not have I would like to copy that record and insert it into Table A. I have tried to use Insert Into Select statements, but I cannot get it to execute. 如果表B包含表A没有的记录,我想复制该记录并将其插入表A。我试图使用Insert Into Select语句,但是无法执行它。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you 谢谢

I have tried to use Insert Into Select statements, but I cannot get it to execute. 我试图使用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

Maybe a NOT EXISTS is what you search for. 搜索的可能是“ 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);

(The WHERE in the exists can possibly be simplified if the tables have primary keys and it is enough to compare them.) (如果表具有主键并且足以对其进行比较,则可以简化存在的WHERE 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM