Use SELECT inside an UPDATE query

后端 未结 6 2113
刺人心
刺人心 2020-11-30 07:51

How can I UPDATE a field of a table with the result of a SELECT query in Microsoft Access 2007.

Here\'s the Select Query:

S         


        
6条回答
  •  臣服心动
    2020-11-30 08:36

    I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:

    UPDATE FUNCTIONS A
    INNER JOIN (
      SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
      FROM TAX BB, FUNCTIONS AA
      WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
      GROUP BY AA.Func_ID
    ) B 
    ON B.Func_ID = A.Func_ID
    SET A.Func_TaxRef = B.MinOfTax_Code
    

    Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:

    UPDATE FUNCTIONS
    INNER JOIN FUNCTIONS_TAX
    ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
    SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
    

    However, this still doesn't work.

    I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:

    UPDATE FUNCTIONS
    SET Func_TaxRef = DLookup(
      "MinOfTax_Code", 
      "FUNCTIONS_TAX", 
      "Func_ID = '" & Func_ID & "'"
    )
    

    Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).

    Good luck!

提交回复
热议问题