2013-04-15 74 views
0

我有一個Access數據庫,我需要每週更新基於固定長度的文本文件訪問SQL查詢添加或更新值

該文件包含一些新的記錄和一些更新。

目前,我正在使用ADODB連接將文件視爲記錄集,循環其記錄並根據需要添加或更新我的記錄。

問題是這個過程非常緩慢,複雜並且會產生一些錯誤。

有沒有辦法使用Access SQL實現相同的結果?

回答

0

我從Excel導入很多東西,並且發現最簡單的方法是將文件導入到一個表中並從中運行所有更新/插入,因爲一旦將數據存儲在本地表中。

您可以即時創建表格,但我更喜歡將表格結構全部設置並使用TransferText導入,您可以在其中使用導入規格。

鬆散設置此:

  1. 創建相應的字段名稱和數據類型的表
  2. 手動從文本文件導入數據,並保存導入規範
  3. 使用VBA導入未來文本文件和觸發更新/插入查詢

代碼可能是這個樣子:

' Folder where files to be imported are saved 
strFilePath = "C:\myFolder\" 

' Look for a .txt file in that folder 

strFileName = Dir(strFilePath & "*.txt") 

' Loop through all .txt files until each is imported 
Do Until strFileName = "" 



strFile = strFilePath & strFileName 

' Import the file to a temporary table where "myImportSpec" is what you saved 
    ' the import spec as when you did the manual import and "tbl_IMPORT_Temp" 
    ' is the table you created to run your queries from 
    'NOTE: This is what i use for .csv files and haven't tested on .txt but 
    ' I think it should work 
DoCmd.TransferText acImportDelim, "myImportSpec", "tbl_IMPORT_Temp", strFile 

DoCmd.OpenQuery "qryUpdateQuery", acViewNormal 
DoCmd.OpenQuery "qryAppendQuery", acViewNormal 

' Copy the .txt file to a new folder 
FileCopy strFile, strFilePath & "Successful\" & strFileName 
' Delete the original file so it isn't imported again 
Kill strFile 

NextFile: 
    ' Clear your temp import table 
    DoCmd.RunSQL "DELETE * FROM tbl_IMPORT_Temp" 
    ' Get the next file to be imported 
    strFileName = Dir(strFilePath & "*.txt") 
Loop 

希望這會有所幫助。 Simon

+0

它適用於一些改編。謝謝! –

2

因爲我不相信Access具有任何種類的「upsert」功能,我的第一個傾向是創建兩個查詢 - 插入查詢和更新查詢 - 並添加一個WHERE子句,以限制插入並更新到適當的記錄。然後你就可以在單個事務,有事下再結合這樣的:

With conn 'Assuming you keep using the ADO recordset; you could use DAO instead 
    .BeginTrans 
    .Execute "UpdateQuery" 
    .Execute "InsertQuery" 
    .CommitTrans 
End With 

也許並不理想,但比一個循環更好。

+0

謝謝你,我會測試它 –

+0

+1這是一個好主意,但是如果db被正確地規範化和定義,就不需要「用WHERE限制插入」。由於PK和唯一索引(es),可能的重複將被丟棄。 –