2

如何构造一个 SQL VBA 块,这样我就可以执行多个 SQL 语句,而不必为每个单独的 SQL 语句打开数据库?

例如,我尝试了以下两个代码块,但得到一个错误,指出 FROM 子句有问题。

   Dim dbs As Database

   Set dbs = OpenDatabase("path\database.mdb")

   dbs.Execute " INSERT INTO table1 (col1,col2,col3) " _
                & "SELECT F1,F2,Format$(Now(),'Short Date') " _
                & "FROM table2" _
                & "DROP table2;"
    dbs.Close

        Dim dbs As Database

        Set dbs = OpenDatabase("path\database.mdb")

        dbs.Execute " INSERT INTO table1 (col1,col2,col3) " _
                    & "SELECT F1,F2,Format$(Now(),'Short Date') " _
                    & "FROM table2 " _
                    & "GO " _
                    & "DROP TABLE table2        
        dbs.Close
4

2 回答 2

4

为什么不直接使用第二个电话.Execute

Dim dbs As Database

Set dbs = OpenDatabase("path\database.mdb")

dbs.Execute "INSERT INTO table1 (col1,col2,col3) " _
            & "SELECT F1,F2,Format$(Now(),'Short Date') " _
            & "FROM table2"

dbs.Execute "DROP TABLE table2"

dbs.Close
于 2013-11-06T17:53:49.857 回答
3

如果您的表链接到访问数据库,那么您可以像这样使用DoCmd.RunSQL&DoCmd.DeleteObject命令:

DoCmd.RunSQL "INSERT INTO table1 (col1, col2, col3) " & _
             "SELECT F1, F2, Format(Date(), 'mm/dd/yyyy') " & _
             "FROM table2"

DoCmd.DeleteObject acTable, "table2"

需要更少的代码,并且不需要打开和关闭连接。

于 2013-11-06T17:52:39.073 回答