【问题标题】:ACCESS VBA - cannot create relationsACCESS VBA - 无法创建关系
【发布时间】:2012-05-05 02:07:37
【问题描述】:

所以举个例子:

Sub CreateRelation()

   Dim db As Database
   Dim rel As Relation
   Dim fld As Field

   Set db = CurrentDb
   Set rel = db.CreateRelation("OrderID", "Orders", "Products")

   'referential integrity
   rel.Attributes = dbRelationUpdateCascade

   'specify the key in the referenced table
   Set fld = rel.CreateField("OrderID")

   fld.ForeignName = "OrderID"

   rel.Fields.Append fld

   db.Relations.Append rel

End Sub

我不断收到错误:

没有为主表的引用字段找到唯一索引。

如果我在这个 sub 之前包含 vba 以在字段的索引中创建,它会给我错误:

索引已经存在。

所以我想弄清楚这一点。如果没有设置任何主键,这会导致它不起作用吗?我对此感到困惑,但我真的很想弄清楚这一点。所以orderIDProducts 表中的外键

【问题讨论】:

    标签: ms-access ms-access-2007 vba


    【解决方案1】:

    “No unique index found for the referenced field of the primary table”的错误是由于OrderId不能是Orders表的主键,并且它不能有唯一索引。

    “索引已存在”的其他错误是由于 Access 将在创建外键时为其添加非唯一索引而导致的。 Products 表中可能已经有一个名为“OrderId”的索引,当您尝试通过代码创建外键时,它会产生冲突。您需要检查 Products 表上的 TableDef.Indexes 集合,以确保在添加外键之前不存在名为“OrderId”的索引。

    【讨论】:

      【解决方案2】:

      您可以通过界面手动创建关系,然后对其进行逆向工程。这是我检查现有关系的即时窗口会话:

      ? currentdb.Relations.Count
       1 
      
      ? currentdb.Relations(0).Name
      parentchild
      
      ? currentdb.Relations(0).Table
      tblParent
      
      ? currentdb.Relations(0).ForeignTable
      tblChild
      
      ? currentdb.Relations(0).Fields.Count
       1 
      
      ? currentdb.Relations(0).Fields(0).Name
      id
      
      ? currentdb.Relations(0).Fields(0).ForeignName
      parent_id
      

      作为参考,这是用于创建该关系的子:

      Public Sub CreateRelationship()
      Dim strSql As String
      strSql = "ALTER TABLE tblChild" & vbNewLine & _
          "ADD CONSTRAINT parentchild" & vbNewLine & _
          "FOREIGN KEY (parent_id) REFERENCES tblParent (id);"
      CurrentProject.Connection.Execute strSql
      End Sub
      

      在您确认已确定哪些是外部表和键之前,请不要使用 dbRelationUpdateCascade 属性。

      【讨论】:

      • 使用 DDL 代替 DAO 通常并不容易。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2020-10-18
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多