1

现在我有一个 MS SQL 数据库,其中包含大约 50 个左右的表,我想使用 DSN Less 连接链接到 MS Access。下面是基本代码,其中我有一个参数 stRemoteTableName,它是要导入的 SQL 表的表名。我可以每次为每张桌子调用这个函数,但这需要很长时间;是否有循环遍历 SQL 数据库中的所有表并将它们传递给该函数以便导入所有表?我很难在网上找到这样的代码,所以非常感谢帮助。

 Private Sub ImportAllTables(stRemoteTableName)
        On Error GoTo AttachDSNLessTable_Err
            Dim td As TableDef
            Dim stConnect As String
            stServer = "C:\Location"
            stDatabase = "DB"
            stLocalTableName = stRemoteTableName
            stUsername = ""

            For Each td In CurrentDb.TableDefs
                If td.Name = stLocalTableName Then
                    CurrentDb.TableDefs.Delete stLocalTableName
                End If
            Next

            stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"

            Set td = CurrentDb.CreateTableDef(stLocalTableName, stRemoteTableName, stConnect)
            CurrentDb.TableDefs.Append td
            Exit Sub

        AttachDSNLessTable_Err:

           AttachDSNLessTable = False
            MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description
        End Sub
4

1 回答 1

1

您可以使用传递查询列出 SQL Server 数据库中的表名。打开基于该查询的记录集。然后循环遍历记录集行并链接每个表。

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strConnect As String
Dim strSelect As String

strSelect = "SELECT t.name FROM sys.tables t;"
'strConnect =  <you already have this as stConnect>
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strSelect)
qdf.Connect = strConnect
Set rs = qdf.OpenRecordset
With rs
    Do While Not .EOF
        ' you want to link; I will just list
        ' the table names
        Debug.Print !name
        .MoveNext
    Loop
    .Close
End With
Set rs = Nothing
Set qdf = Nothing
Set db = Nothing
于 2013-07-08T22:04:39.610 回答