【问题标题】:How to change database for linked tables in Access MDB如何在 Access MDB 中更改链接表的数据库
【发布时间】:2017-03-15 15:18:36
【问题描述】:

我有许多 Access 数据库文件,其中包含指向 SQLServer 数据库的链接表。现在数据库服务器已更改,我必须编辑链接,可能无需重新创建它们。

有可能吗?我使用 Access 2013。

【问题讨论】:

  • 这取决于表是否使用静态 ODBC 连接链接。如果是,您所要做的就是使用新的服务器信息更新该连接。

标签: sql-server vba ms-access ms-access-2013


【解决方案1】:

是的,可以使用 VBA 进行操作,但是您执行此操作的方式实际上取决于您链接表格的方式。

这是我用于 SQL 服务器表的 2 个连接字符串示例

直接连接:

Driver=SQL Server Native Client 10.0;Server=server_name;Address=server_address,1433;Network=network_name;Database=database_name;Trusted_Connection=Yes

DSN 连接(在 ODBC 控制面板中有一个条目)

ODBC;Provider=SQLNCLI10;Server=server_name;DSN=name_of_DSN_entry_in_ODBC_control_panel;Database=database_name;Trusted_Connection=Yes

所以首先要做的是确定您的表是如何链接的。 您可以使用此代码(注意 cmets):

Public Sub Check_ODBC_tables()
    Dim tdef As TableDef

    ' First loop on all tables to determine the connection strings

    For Each tdef In CurrentDb.TableDefs

        ' only print the constring if the database name is your old database (adapt accordingly)
        If InStr(tdef.Connect, "Database=old_database_name") Then
            Debug.Print tdef.Connect
        End If
    Next

End Sub

运行此代码 (F5) 并检查即时窗口中的输出。您会发现表格是如何链接的以及连接字符串是什么。

您应该根据它准备一个连接字符串,并在其中调整数据库名称以使用您的新数据库。

准备就绪后,您可以调整并运行以下代码,该代码将删除旧表并使用新数据库名称重新创建它们(可能需要进行一些调整),因此请在调试模式下考虑!

Public Sub Change_ODBC_tables()

    Dim tDef As TableDef
    Dim tDefNew As TableDef

    Dim strTable As String
    Dim strCOnString As String

    ' examples of constrings - ADAPT!!!!
    strCOnString = "Driver=SQL Server Native Client 10.0;Server=server_name;Address=server_address,1433;Network=network_name;Database=database_name;Trusted_Connection=Yes"
    strCOnString = "ODBC;Provider=SQLNCLI10;Server=server_name;DSN=name_of_DSN_entry_in_ODBC_control_panel;Database=database_name;Trusted_Connection=Yes"

    For Each tDef In CurrentDb.TableDefs

        If InStr(tDef.Connect, "Database=old_database_name") Then

            ' We find a match, store the table name
            strTable = tDef.Name

            ' delete the linked table
            DoCmd.DeleteObject acTable, strTable

            ' recreate the linked table with new DB name
            Set tDef2 = CurrentDB.CreateTableDef(strTable)
            tDef2.Connect = strCOnString
            tDef2.SourceTableName = strTable
            tDef2.Name = strTable
            CurrentDb.TableDefs.Append tDef2

        End If
    Next


End Sub

如果您不完全理解我发布的第二段代码,我建议您在运行之前备份您的 mdb,因为它会删除可能导致严重问题的对象。

【讨论】:

  • +1,但不是DB.CreateTableDef 和它后面的代码块,我会使用DoCmd.TransferDatabase acLink(参见here)。它更短,我认为它在识别源表中的 PK 方面做得更好。
  • 假设只有服务器位置没有改变表定义。从字面上看,你可以做到。 tdf.connect = NewConstr, TDF.RefreshLink
猜你喜欢
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
相关资源
最近更新 更多