Update Existing Access Records from CSV Import , native to MS Access or in VB.NET

倾然丶 夕夏残阳落幕 提交于 2019-12-02 05:15:56

Essentially, you will have to do a series of action queries: append, update, and delete that use filters and joins. You can save queries as stored queries and call them by DoCmd.OpenQuery, or you can write them in VBA as strings to be passed into DoCmd.RunSQL sqlStatement or CurrentDb.Excecute sqlStatement

IMPORT

First, import the CSV using DoCmd.TransferText acImportDelim into a temporary table. Be sure to clean out previous csv data from temp table prior to import.

DELETE FROM tempTable;

UPDATE

Then, update existing records between temp and live table but condition for existing customers in live table. In Access SQL, joins can be used in update queries but you may run into not updateable queries:

UPDATE tempTable INNER JOIN liveTable 
ON tempTable.CustomerID = liveTable.CustomerID
SET liveTable.Col1 = tempTable.Col1,
    liveTable.Col2 = tempTable.Col2,
    liveTable.Col3 = tempTable.Col3, 
    ... ;

Alternatively, to bypass non-updateable query:

UPDATE liveTable
SET liveTable.Col1 = DLookUp("Col1", "tempTable", "CustomerID=" & liveTable.CustomerID),
    liveTable.Col2 = DLookUp("Col2", "tempTable", "CustomerID=" & liveTable.CustomerID),
    liveTable.Col3 = DLookUp("Col3", "tempTable", "CustomerID=" & liveTable.CustomerID), 
    ... 
WHERE CustomerID IN 
    (SELECT CustomerID FROM tempTable);

Once done, clean out records just updated from temp table (to not conflict with append step and duplicate entries):

DELETE FROM tempTable 
WHERE CustomerID IN 
      (SELECT CustomerID FROM liveTable);

APPEND

Finally, append new records from temp table into live table but condition for customers NOT in live table which you can do with the LEFT JOIN ... NULL:

INSERT INTO (Col1, Col2, Col3 ...) 
SELECT Col1, Col2, Col3 ... 
FROM tempTable LEFT JOIN liveTable 
ON tempTable.CustomerID = liveTable.CustomerID
WHERE liveTable.CustomerID Is Null;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!