Reputation: 15
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.
Upvotes: 0
Views: 1479
Reputation: 375
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
Upvotes: 2
Reputation: 107567
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
...
Upvotes: 1