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

时间:2016-11-02 10:36:03

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

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

可以这样做吗?我使用Access 2013。

1 个答案:

答案 0 :(得分:2)

是的,可以使用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

所以要做的第一件事就是确定表的链接方式。 您可以使用此代码(注意评论):

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

相关问题