简体   繁体   中英

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. 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. 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 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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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