DSN-Less与多个表的连接

时间:2013-07-08 21:23:04

标签: sql database ms-access access-vba dsn

现在我有一个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

1 个答案:

答案 0 :(得分: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