0

I'd like to build a dynamic SQL query that can read from different tables depending on a variable.

So I have a snippet like this:

strSQL = "SELECT a100z.f05, a100z.f10, a100z.f23 ..." 

I'd like to use a variable to specify the '100', as I have a number of similarly named tables: a100, a200, a300, and so on. Only one table is used per query, but different for different queries.

The variable used would be the result from field F of another query.

I could just call separate queries each time I need a specific table, but I'm interested in how to do it this way.

Is this possible, and how should it be written?

1 Answer 1

3

It seems you're using the table name to qualify the field names in the SELECT clause. Consider using an alias for the table name, and then you can qualify the field names with that alias instead. That approach would mean you could reuse the same query and only need to change the table name in the FROM clause.

Something like this ...

strSQL = "SELECT t.f05, t.f10, t.f23" & vbCrLf & _
    "FROM [YourTable] AS t;"

I'm unsure how neatly that suggestion meshes with the rest of your code; it sort of depends on where and how you're using the SELECT query. But if it's used to open a recordset, for example, you could use Replace() to substitute just the table name ...

Dim rs As DAO.Recordset
Dim db As DAO.Database
Set db = CurrentDb
Set rs = db.OpenRecordset(Replace(strSQL, "YourTable", "a100"))

This would be easier if Access let you use a query parameter for the table name. Unfortunately, Access does not allow that flexibility.

As a side point, it seems you may have multiple tables with the same structure. In many cases, a better design is to use a single table with an additional field which you can use to distinguish between the data subsets which were formerly contained in the separate tables. If such a redesign is possible in your situation, you may find the query task is simpler afterward.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.