我有一个 Access 数据库,我需要根据固定长度的文本文件每周更新
该文件包含一些新记录和一些更新。
目前,我正在使用 ADODB 连接将文件视为记录集,循环通过其记录并在需要时添加或更新我的记录。
问题是这个过程非常缓慢、复杂并且会产生一些错误。
有没有办法使用 Access SQL 实现相同的结果?
由于我不相信 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
也许不理想,但比循环更好。
我做了很多从 Excel 导入的工作,发现最简单的方法是将文件导入表并从中运行所有更新/插入,因为一旦您在本地表中拥有数据,它实际上会更快。
您可以即时创建表,但我更喜欢设置表结构并使用 TransferText 导入,您可以在其中使用导入规范。
松散地设置它:
代码可能如下所示:
' 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
希望这可以帮助。西蒙