简体   繁体   中英

MS Access SQL - Update field in one table with a count from another table

I have a table called 'FilesUploaded' which has a summary of all files uploaded to my access DB. I want to add a field in here that contains the count of all errors from another table.

  • My FilesUploaded table contains a field called 'FileName' which has the full name of the file.
  • I want to get a count of all records in table1 where the 'ValidityCheck' field contains 'Error'. Table1 also contains a field called 'Name_of_Report' which has the file name which will match back to the FilesUploaded table.
  • The 'vFileName' variable will contain what is in both the 'Filename' field and the 'Name_of_Report' field

The below is the code I have tried using, but it says this type of join is not allowed and I have no idea what other way I can achieve this.

Call RunSQL("UPDATE FilesUploaded " & _
    "LEFT JOIN (SELECT table1.Name_of_Report, Sum(IIf([table1].[ValidityCheck] Like '*Error*',1,0)) AS ErrorCount FROM table1 GROUP BY table1.Name_of_Report) AS temp on temp.Name_of_Report = FilesUploaded.FileName " & _
    "SET " & _
    "FilesUploaded.[ErrorCount] = temp.ErrorCount " & _
    "WHERE FilesUploaded.[FileName] = '" & vFileName & "' ")

Does anybody know a different way can update the FilesUploaded table with a count of the ValidityCheck field from the Table1 table?

In MS Access, UPDATE...JOIN requires its analogous SELECT...JOIN to be updateable . Aggregate queries using SUM are not updateable queries. Therefore, consider domain functions like DSum .

Additionally, consider a stored query and call it in VBA with parameterization via QueryDefs . Do note the use of ALIKE to use % for wildcards in case you need to run query outside of the MS Access GUI such as in ODBC or OLEDB connections where * is not recognized.

SQL (save as a stored query)

PARAMETERS paramFileName TEXT;
UPDATE FilesUploaded f
SET f.[ErrorCount] = DSUM("*", "table1", 
                          "[ValidityCheck] ALIKE '%Error%' AND [Name_of_Report]='" & f.[FileName] & "'")
WHERE f.[FileName] = [paramFileName];

VBA (run query without string concatenation)

Dim qdef As QueryDef

Set qdef = CurrentDb.QueryDefs("mySavedQuery")    

qdef![paramFileName] = vFileName     ' BIND PARAM VALUE
qdef.Execute                         ' RUN ACTION QUERY

Set qdef = Nothing

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