简体   繁体   中英

MS Access VBA: dynamic SQL

Inside of a function, I am using a string to run sql. I need to vary some of the string dependent on user selection. For brevity, I have included only one field from each table. Also, these are not the real table names.

strSQL = "DELETE * FROM tblWax"
db.Execute strSQL, dbFailOnError

strSQL = "INSERT INTO tblWax ( strPortName, lngShortSet ) " & _
         "SELECT tblAAA.strPastName, tblBBB.lngShortID " & _
         "FROM tblAAA INNER JOIN tblBBB ON tblAAA.Parameter = tblBBB.Parameter"
db.Execute strSQL, dbFailOnError

I would like to substitute tblSSS for tblBBB depending on user choice and with that same choice (within the field strChoice), tblWax needs to be tblHat. That is: if strChoice = 1, then tblWax, tblAAA, tblBBB if strChoice = 2, then tblHat, tblAAA, tblSSS

Otherwise, the rest of the string(s) is identical.

Simply use conditional logic like VBA's SELECT...CASE

Select Case strChoice

   Case 1
      strSQL = "DELETE * FROM tblWax"
      db.Execute strSQL, dbFailOnError

      strSQL = "INSERT INTO tblWax ( strPortName, lngShortSet ) " & _
               "SELECT tblAAA.strPastName, tblBBB.lngShortID " & _
               "FROM tblAAA INNER JOIN tblBBB ON tblAAA.Parameter = tblBBB.Parameter"

   Case 2
      strSQL = "DELETE * FROM tblHat"
      db.Execute strSQL, dbFailOnError

      strSQL = "INSERT INTO tblHat ( strPortName, lngShortSet ) " & _
               "SELECT tblAAA.strPastName, tblSSS.lngShortID " & _
               "FROM tblAAA INNER JOIN tblSSS ON tblAAA.Parameter = tblSSS.Parameter"

End Select

db.Execute strSQL, dbFailOnError

You can even use multiple values in one case

Case 1, 3, 5
...
Case 2, 4, 6
...

And use an Else for the rest that do not follow other Case statements

Case Else
...

To expand on @Smandoli's and @Gustav's answer on using string variables for the table names. This allows you to create multiple cases without the variable names getting lost in the SQL string.

Select Case strChoice

    Case 1:
        strTarget = "tblWax"
        strJoin = "tblBBB"

    Case 2:
        strTarget = "tblHat"
        strJoin = "tblSSS"

end select

strSQL = "DELETE * FROM " & strTarget
db.Execute strSQL, dbFailOnError

strSQL = "INSERT INTO " & strTarget & " ( strPortName, lngShortSet ) " & _
         "SELECT tblAAA.strPastName, " & strJoin & ".lngShortID " & _
         "FROM tblAAA INNER JOIN " & strJoin & _
         " ON tblAAA.Parameter = " & strJoin & ".Parameter"

db.Execute strSQL, dbFailOnError

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