2016-11-02 10 views
0

SQLServerデータベースへのリンクテーブルを含むAccessデータベースファイルが多数あります。今度はデータベースサーバーが変更されたため、リンクを編集する必要があります。再作成する必要はありません。Access MDBでリンクテーブルのデータベースを変更する方法

これは可能ですか?私はAccess 2013を使用しています。

+0

テーブルが静的ODBC接続を使用してリンクされているかどうかによって異なります。そうであれば、その接続を新しいサーバー情報で更新するだけです。 – SunKnight0

答えて

2

はい、VBAで行うことはできますが、実際に行う方法は実際にテーブルをリンクする方法によって異なります。ここ

私はSQL Serverのテーブルに使用する接続文字列の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)とイミディエイトウィンドウで出力を確認してください: あなたは(コメントに注意を払う)このコードを使用することができます。テーブルがどのようにリンクされ、どのような接続文字列が見つかっているでしょうか。

これに基づいて接続文字列を準備し、新しいDBを使用するためにデータベース名を変更する必要があります。

準備ができたら、古いテーブルを削除し、新しいデータベース名で再作成するコードをいくつか修正して実行することができます(いくつかの調整が必要な場合があります)。

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 

あなたは完全に私が投稿コードの2番目の部分を理解していない場合、それは深刻な問題を引き起こす可能性がありますオブジェクトを削除しますので、私はそれを実行するために、あなたのmdbは前のバックアップにあなたを促します。

+1

+1ですが、 'DB.CreateTableDef'の代わりに、コードブロックの後に' DoCmd.TransferDatabase acLink'を使用します([here](http://stackoverflow.com/a/36897853/3820271)を参照)。短くて、ソーステーブルのPKを識別するのがより良い仕事だと思います。 – Andre

+0

は、サーバーの場所のみがテーブル定義ではなく変更されていると仮定しています。文字通り、あなたはただ行うことができます。 tdf.connect = NewConstr、TDF.RefreshLink –

関連する問題