如何更改 Access MDB 中链接表的数据库

How to change database for linked tables in Access MDB

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

可以吗?我使用 Access 2013.

是的,可以用 VBA 来做,但是你做这件事的方式实际上取决于你如何链接 tables。

这是我用于 SQL 服务器 tables

的 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

因此,首先要做的是确定您的 table 是如何链接的。 可以使用这段代码(注意注释):

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) 并立即检查输出 window。您会发现 table 是如何链接的以及连接字符串是什么。

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

准备就绪后,您可以调整 运行 以下代码,删除旧的 table 并使用新的数据库名称重新创建它们(可能需要进行一些调整),所以去吧认为它处于调试模式!

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,因为它会删除可能导致严重问题的对象。