简体   繁体   English

DSN-Less连接多个表

[英]DSN-Less Connection with multiple tables

Right now I have an MS SQL database with about 50 or so tables in it with which I'd like to link to MS Access using a DSN Less connection. 现在,我有一个MS SQL数据库,其中包含大约50个左右的表,我想使用DSN Less连接来链接到MS Access。 Below is the basic code where I have a parameter of stRemoteTableName which is the table name of the SQL table to import. 下面是基本代码,其中有一个参数stRemoteTableName,它是要导入的SQL表的表名。 I could call this function each time for each table but that would take forever; 我可以为每个表每次调用此函数,但这将永远花费; is there anyway to loop through all tables in an SQL database and pass them to this function so that all tables are imported? 无论如何,要遍历SQL数据库中的所有表并将它们传递给此函数,以便导入所有表? I'm having a very hard time finding any code online for something like this, so help is much appreciated. 我很难在网上找到类似这样的代码,因此非常感谢您的帮助。

 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

You can use a pass-through query to list the table names from your SQL Server database. 您可以使用传递查询从SQL Server数据库中列出表名称。 Open a recordset based on that query. 打开基于该查询的记录集。 Then loop through the recordset rows and link each table. 然后遍历记录集行并链接每个表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM