How to rename MS Access table with relationships using SQL?

社会主义新天地 提交于 2020-01-06 06:03:38

问题


I'm connecting to an MS Access database from an external .Net application. I need to use SQL in order to upgrade the schema of the database. Part of the upgrade requires renaming a table that is part of a 1-to-many relationship.

I understand that it is not possible to actually rename a table in MS Access using SQL. My research has led me to the following solution.

SELECT * INTO OldTableName FROM NewTableName
DROP TABLE OldTableName

This appears to work correctly for tables that are not part of a relationship. However, if the table belongs to a relationship, then I receive the following exception when running the DROP TABLE SQL.

Cannot delete this index or table.  It is either the current index or is used in a relationship.

Is there a way via SQL that I can update the relationship in MS Access to point to the new table that has been created so the old table can be dropped?


回答1:


You can probably save yourself some grief by simply using Access DAO to rename the table:

using Microsoft.Office.Interop.Access.Dao;

namespace AccessDaoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var dbe = new DBEngine();
            Database db = dbe.OpenDatabase(@"C:\Users\Public\Database1.accdb");
            TableDef tbd = db.TableDefs["OldTableName"];
            tbd.Name = "NewTableName";
            db.Close();
        }
    }
}

The .NET project will require a COM reference for Access DAO. The one I used was

Microsoft Office 14.0 Access Database Engine Object Library




回答2:


You should drop foreign key constrain first. How to do this using SQL you can see for instance here. Then create new constraint:

alter table City
   add constraint FK_City_REF_States foreign key (ID_State)
      references States (ID_State);


来源:https://stackoverflow.com/questions/45339956/how-to-rename-ms-access-table-with-relationships-using-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!