2017-04-18 99 views
0

在函數內部,我使用了一個字符串來運行sql。我需要根據用戶選擇改變一些字符串。爲簡潔起見,我在每張表中只包含一個字段。而且,這些不是真正的表名。MS Access VBA:動態SQL

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 

我想替代tblSSS爲tblBBB取決於用戶的選擇,並使用同樣的選擇(場strChoice內),tblWax需要被tblHat。那就是: 如果strChoice = 1,則tblWax,tblAAA,tblBBB 如果strChoice = 2,則tblHat,tblAAA,tblSSS

否則,串(一個或多個)的其餘部分是相同的。

回答

1

要展開@ Smandoli's和@ Gustav關於爲表名使用字符串變量的答案。這使您可以創建多個案例,而不會使SQL字符串中的變量名稱迷失。

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 
1

只需使用條件邏輯VBA類似的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 

你甚至可以在一種情況下

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

使用多個值,並使用Else對於不遵循其他Case陳述

休息
Case Else 
... 
+3

這可以通過在SQL中使用字符串變量來重構,例如'strTargetTable =「tblWax」'。 – Smandoli

+1

確實。 SQL不會更改,因此請使用_select-case_來確定表名,然後用表名替換SQL中的佔位符。 – Gustav

+0

我確實喜歡選擇案例,但案件數量很少,現在可能還沒有。因此,我將使用select case將變量更改爲表名,並將該變量放入SQL中。謝謝大家。 – random13