且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用新数据替换 SQL 数据表

更新时间:2023-12-05 13:16:58

如果你想在转移新的目标表之前删除现有的目标表,那么代码会更像这样:

If you want to DROP the existing destination table before transferring the new one then the code would be more like this:

Option Compare Database
Option Explicit

Public Function TransferTableToSqlServer()
    Dim cdb As dao.Database, qdf As dao.QueryDef
    Dim err As dao.Error
    Const DestinationTableName = "AC_CDData"
    Const ConnectionString = _
            "ODBC;" & _
                "Driver={SQL Server Native Client 10.0};" & _
                "Server=(local)\SQLEXPRESS;" & _
                "Database=YourDatabaseName;" & _
                "UID=YourSqlUserId;" & _
                "PWD=YourSqlPassword;"
    Set cdb = CurrentDb
    Set qdf = cdb.CreateQueryDef("")
    qdf.Connect = ConnectionString
    qdf.sql = _
            "IF EXISTS " & _
                "(" & _
                    "SELECT * FROM INFORMATION_SCHEMA.TABLES " & _
                    "WHERE TABLE_NAME='" & DestinationTableName & " '" & _
                ") " & _
            "DROP TABLE [" & DestinationTableName & "]"
    qdf.ReturnsRecords = False
    On Error GoTo TransferTableToSqlServer_qdfError
    qdf.Execute dbFailOnError
    On Error GoTo 0
    Set qdf = Nothing
    Set cdb = Nothing
    DoCmd.TransferDatabase _
            acExport, _
            "ODBC Database", _
            ConnectionString, _
            acTable, _
            "CDData", _
            DestinationTableName, _
            False
    Exit Function

TransferTableToSqlServer_qdfError:
    For Each err In dao.Errors
        MsgBox err.Description, vbCritical, "Error " & err.Number
    Next
End Function