Access SQL Query from another DB

后端 未结 2 1171
无人及你
无人及你 2021-01-15 04:40

I want to apply an SQL query to one Access table, from which it is retrieving data from a table in another Access file. I\'ve looked around on this subject and can\'t seem t

相关标签:
2条回答
  • 2021-01-15 05:18

    You prefer not to use a link to the table in the external database, but that choice is a complication when you want to use DAvg. However, since you're doing this with VBA code, you can ditch DAvg and do what you need in 2 steps:

    1. First retrieve the average from the external table.
    2. Use that step #1 average in your UPDATE.

    For step #1, test this as a new query in the Access query designer ...

    SELECT Avg(Field1InExternalDB)
    FROM TableInExternalDB IN 'C:\VB\ExternalDB.accdb'
    WHERE Field2InExternalDB=Year(Date());
    

    Assuming that query returns the correct value, adapt your VBA code to retrieve the same value.

    Dim db As DAO.database
    Dim strSelect As String
    Dim varAvg As Variant
    strSelect = "SELECT Avg(Field1InExternalDB)" & vbCrLf & _
        "FROM TableInExternalDB IN 'C:\VB\ExternalDB.accdb'" & vbCrLf & _
        "WHERE Field2InExternalDB=Year(Date());"
    'Debug.Print strSelect
    Set db = CurrentDb
    varAvg = db.OpenRecordset(strSelect)(0)
    Debug.Print Nz(varAvg, 0) ' see note
    

    Note that query will return Null when no rows include Field2InExternalDB values which match the current year. That is why varAvg is declared as Variant. Later Nz(varAvg, 0) will give you zero instead of Null.

    Then you can use a parameter query for your UPDATE and supply Nz(varAvg, 0) as the parameter value.

    Dim qdf As DAO.QueryDef
    Dim strUpdate As String
    strUpdate = "UPDATE TableInCurrentDB" & vbCrLf & _
        "SET [Field1InCurrentDB]=[pAvg]" & vbCrLf & _
        "WHERE [Field2InCurrentDB]='1';"
    'Debug.Print strUpdate
    Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
    qdf.Parameters("pAvg") = Nz(varAvg, 0)
    qdf.Execute dbFailOnError
    Set qdf = Nothing
    Set db = Nothing
    
    0 讨论(0)
  • 2021-01-15 05:18

    Could you not do this as a single step? Incorporate the output of the first SQL as the input to the "set" in the second?

    In other words,bypass the first query and just do the second using this as the "strUpdate" string:

    strUpdate = "UPDATE TableInCurrentDB" & vbCrLf & _
        "SET [Field1InCurrentDB]=" & vbCrLf & _
        "  (SELECT Val(Nz(Avg(Field1InExternalDB),0))" & vbCrLf & _
        "   FROM TableInExternalDB IN 'C:\VB\ExternalDB.accdb'" & vbCrLf & _
        "   WHERE Field2InExternalDB=Year(Date()) )" & vbCrLf & _
        "WHERE [Field2InCurrentDB]='1';"
    
    0 讨论(0)
提交回复
热议问题